diff --git a/index.html b/index.html index c7de9b8..4c951c4 100644 --- a/index.html +++ b/index.html @@ -29,8 +29,8 @@

Profile viewer

- + diff --git a/scripts/rdflib.min.js b/scripts/rdflib.min.js index dbb9e07..a5f4025 100644 --- a/scripts/rdflib.min.js +++ b/scripts/rdflib.min.js @@ -1,4 +1,5 @@ -'undefined'==typeof window||window.solid||(window.solid={}),function e(t,n){'object'==typeof exports&&'object'==typeof module?module.exports=n(require('window'),require('solid-auth-client')):'function'==typeof define&&define.amd?define(['window'],n):'object'==typeof exports?exports.$rdf=n(require('window'),require('solid-auth-client')):t.$rdf=n(t.window,t.solid.auth)}(window,function(e,t){var n=Math.pow,a=Math.floor,r=String.fromCharCode,o=Math.abs;return function(e){function t(a){if(n[a])return n[a].exports;var r=n[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,a){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:a})},t.r=function(e){'undefined'!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:'Module'}),Object.defineProperty(e,'__esModule',{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&'object'==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(t.r(a),Object.defineProperty(a,'default',{enumerable:!0,value:e}),2&n&&'string'!=typeof e)for(var r in e)t.d(a,r,function(t){return e[t]}.bind(null,r));return a},t.n=function(e){var n=e&&e.__esModule?function t(){return e['default']}:function t(){return e};return t.d(n,'a',n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p='',t(t.s=59)}([function(e,t,n){'use strict';function a(e){return a='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function e(t){return typeof t}:function e(t){return t&&'function'==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?'symbol':typeof t},a(e)}function r(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function o(e,t){for(var n=0,a;na?null:new t(n.slice(0,a+1))}},{key:'site',value:function e(){var n=this.uri.split('#')[0],a=n.indexOf('//');if(0>a)throw new Error('This URI does not have a web site part (origin)');var r=n.indexOf('/',a+2);if(0>r)throw new Error('This URI does not have a web site part. (origin)');return new t(n.slice(0,r+1))}},{key:'doc',value:function e(){return 0>this.uri.indexOf('#')?this:new t(this.uri.split('#')[0])}},{key:'toString',value:function e(){return'<'+this.uri+'>'}},{key:'uri',get:function e(){return this.value},set:function e(t){this.value=t}}],[{key:'fromValue',value:function e(n){if('undefined'==typeof n||null===n)return n;var a=n&&n.termType;return a?n:new t(n)}}]),t}(h);f.termType='NamedNode',f.prototype.classOrder=c.NamedNode,f.prototype.isVar=0,e.exports=f},function(e,t,n){'use strict';function a(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function r(e,t){for(var n=0,a;nt.classOrder?1:this.valuet.value?1:0}},{key:'equals',value:function e(t){return!!t&&this.termType===t.termType&&this.value===t.value}},{key:'hashString',value:function e(){return this.toCanonical()}},{key:'sameTerm',value:function e(t){return this.equals(t)}},{key:'toCanonical',value:function e(){return this.toNT()}},{key:'toNT',value:function e(){return this.toString()}},{key:'toString',value:function e(){throw new Error('Node.toString() is abstract - see the subclasses instead')}}]),e}();e.exports=i,i.fromValue=function e(t){var a=n(17),r=n(11),o=n(0);if('undefined'==typeof t||null===t)return t;var i=t&&t.termType;return i?t:Array.isArray(t)?new a(t):r.fromValue(t)},i.toJS=function e(t){return t.elements?t.elements.map(i.toJS):t.datatype?t.datatype.equals(ns.xsd('boolean'))?'1'===t.value:t.datatype.equals(ns.xsd('dateTime'))||t.datatype.equals(ns.xsd('date'))?new Date(t.value):t.datatype.equals(ns.xsd('integer'))||t.datatype.equals(ns.xsd('float'))||t.datatype.equals(ns.xsd('decimal'))?+t.value:t.value:t}},function(e,t,n){function a(e){var t;return t=e.indexOf('#'),0>t?e:e.slice(0,t)}function r(e){return new p(a(e.uri))}function o(e){var t=/[^\/]*\/\/([^\/]*)\//.exec(e);return t?t[1]:''}function i(e,t){var n=t.indexOf('#'),a,r,o,i,s,d;if(0a)return l('Invalid base: '+t+' in join with given: '+e),e;if(r=t.slice(0,+a+1||9e9),0===e.indexOf('//'))return r+e;if(t.indexOf('//',a)===a+1){if(o=t.indexOf('/',a+3),0>o)return 0o)return 0s)return r+e;for(0<=s&&st?null:e.slice(0,t)}function d(e,t){var a=/^[-_a-zA-Z0-9.]+:(\/\/[^\/]*)?\/[^\/]*$/,r,d,i,u,l,c,h,n,o,p,f,g,m;if(!e)return t;if(e===t)return'';for(d=n=0,l=t.length;ni&&(i=-2),u=t.indexOf('/',i+2),'/'!==t[u+1]&&'/'!==e[u+1]&&t.slice(0,u)===e.slice(0,u)))return t.slice(u);if('#'===t[d]&&e.length===d)return t.slice(d);for(;0d)return t;if(0=g;1<=g?++p:--p)m+='../';return m+t.slice(d)}var l=l||console.log;e.exports.docpart=a,e.exports.document=r,e.exports.hostpart=o,e.exports.join=i,e.exports.protocol=s,e.exports.refTo=d;var p=n(0)},function(e,t){var n;n=function(){return this}();try{n=n||Function('return this')()||(1,eval)('this')}catch(t){'object'==typeof window&&(n=window)}e.exports=n},function(e,t,n){(function(e){function t(e,t,n){var a=null;if('undefined'!=typeof e.fetcher)a=e.fetcher;else return;if('NamedNode'===t.termType){var r=y(t.uri),o;if(0>t.uri.indexOf('#')){if(f(t.uri,'http://dbpedia.org/resource/Category:'))return;f(t.uri,'http://purl.org/dc/elements/1.1/')||f(t.uri,'http://purl.org/dc/terms/')?o='http://dublincore.org/2005/06/13/dcq':f(t.uri,'http://xmlns.com/wot/0.1/')?o='http://xmlns.com/wot/0.1/index.rdf':f(t.uri,'http://web.resource.org/cc/')&&(o='http://web.resource.org/cc/schema.rdf')}return(o&&(r=o),!(a&&'unrequested'!==a.getState(r)))?(o&&b.warn('Assuming server still broken, faking redirect of <'+t.uri+'> to <'+r+'>'),a.fetch(r,{referringTerm:n})):void 0}}function a(e,t,n){n||(n=0);var a=e.length;for(0>n&&(n=a+n);n/g,'>').replace(/'/g,'"')+'\'')}}if(0\n':''}}}else if(8===e.nodeType)r+='';else if(3===e.nodeType||4===e.nodeType){var c=e.nodeValue.replace(/\n+$/,'');r+=o[o.length-1]?c:c.replace(/&/g,'&').replace(//g,'>')}else console.log('Warning; Cannot handle serialising nodes of type: '+e.nodeType),console.log(e);return r}function d(){var e=new Date,t=e.getYear()+1900,n=e.getMonth()+1,a=e.getDate(),r=e.getUTCHours(),o=e.getUTCMinutes(),i=e.getSeconds();return 10>n&&(n='0'+n),10>a&&(a='0'+a),10>r&&(r='0'+r),10>o&&(o='0'+o),10>i&&(i='0'+i),t+'-'+n+'-'+a+'T'+r+':'+o+':'+i+'Z'}function l(e,t,n,a){var r=function e(t){return'BlankNode'===t.termType?null:t},o=function e(t){var a=n.statementsMatching(t).map(function(e){return''+r(e.subject)+' '+r(e.predicate)+' '+r(e.object)}).concat(n.statementsMatching(void 0,void 0,t).map(function(e){return''+r(e.subject)+' '+r(e.predicate)+' '+r(e.object)}));return a.sort(),a.join('\n')};return'BlankNode'===e.termType&&'BlankNode'===t.termType?0===e.compareTerm(t)?0:o(e)>o(t)?1:o(e)t.classOrder?1:this.idt.id?1:0}},{key:'copy',value:function e(n){var a=new t;return n.copyTo(this,a),a}},{key:'toCanonical',value:function e(){return'_:'+this.value}},{key:'toString',value:function e(){return t.NTAnonymousNodePrefix+this.id}}]),t}(h);f.nextId=0,f.termType='BlankNode',f.NTAnonymousNodePrefix='_:',f.prototype.classOrder=c.BlankNode,f.prototype.isBlank=1,f.prototype.isVar=1,e.exports=f},function(e,t){e.exports='function'==typeof Object.create?function e(t,n){t.super_=n,t.prototype=Object.create(n.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:function e(t,n){t.super_=n;var a=function(){};a.prototype=n.prototype,t.prototype=new a,t.prototype.constructor=t}},function(e,t,n){'use strict';function a(e){return this instanceof a?void(l.call(this,e),p.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once('end',r)):new a(e)}function r(){this.allowHalfOpen||this._writableState.ended||i.nextTick(o,this)}function o(e){e.end()}var i=n(18),s=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=a;var d=n(14);d.inherits=n(7);var l=n(46),p=n(30);d.inherits(a,l);for(var u=s(p.prototype),c=0,h;ca.indexOf('e')&&o(n)<=Number.MAX_SAFE_INTEGER?Number.isInteger(n)?m.integer:m.decimal:m.double,new t(a,null,r)}},{key:'fromValue',value:function e(n){if('undefined'==typeof n||null===n)return n;if('object'===a(n)&&n.termType)return n;switch(a(n)){case'object':if(n instanceof Date)return t.fromDate(n);case'boolean':return t.fromBoolean(n);case'number':return t.fromNumber(n);case'string':return new t(n);}throw new Error('Can\'t make literal from '+n+' of type '+a(n))}}]),t}(g);y.termType='Literal',y.prototype.classOrder=h.Literal,y.prototype.datatype=m.string,y.prototype.lang='',y.prototype.isVar=0,e.exports=y},function(e,t){},function(e,t,n){(function(e){function a(e,t){this._id=e,this._clearFn=t}var r='undefined'!=typeof e&&e||'undefined'!=typeof self&&self||window,o=Function.prototype.apply;t.setTimeout=function(){return new a(o.call(setTimeout,r,arguments),clearTimeout)},t.setInterval=function(){return new a(o.call(setInterval,r,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},a.prototype.unref=a.prototype.ref=function(){},a.prototype.close=function(){this._clearFn.call(r,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;0<=t&&(e._idleTimeoutId=setTimeout(function t(){e._onTimeout&&e._onTimeout()},t))},n(62),t.setImmediate='undefined'!=typeof self&&self.setImmediate||'undefined'!=typeof e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate='undefined'!=typeof self&&self.clearImmediate||'undefined'!=typeof e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(3))},function(e,t,n){(function(e){function n(e){return Array.isArray?Array.isArray(e):'[object Array]'===m(e)}function a(e){return'boolean'==typeof e}function r(e){return null===e}function o(e){return null==e}function i(e){return'number'==typeof e}function s(e){return'string'==typeof e}function d(e){return'symbol'==typeof e}function l(e){return void 0===e}function p(e){return'[object RegExp]'===m(e)}function u(e){return'object'==typeof e&&null!==e}function c(e){return'[object Date]'===m(e)}function h(t){return'[object Error]'===m(t)||t instanceof Error}function f(e){return'function'==typeof e}function g(e){return null===e||'boolean'==typeof e||'number'==typeof e||'string'==typeof e||'symbol'==typeof e||'undefined'==typeof e}function m(e){return Object.prototype.toString.call(e)}t.isArray=n,t.isBoolean=a,t.isNull=r,t.isNullOrUndefined=o,t.isNumber=i,t.isString=s,t.isSymbol=d,t.isUndefined=l,t.isRegExp=p,t.isObject=u,t.isDate=c,t.isError=h,t.isFunction=f,t.isPrimitive=g,t.isBuffer=e.isBuffer}).call(this,n(49).Buffer)},function(e,t,n){function a(e){return a='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function e(t){return typeof t}:function e(t){return t&&'function'==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?'symbol':typeof t},a(e)}function r(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function o(e,t){for(var n=0,a;n']=[f],0<=g(t,'sameAs')&&(this.propertyActions['']=[function(e,t,n,a,r){return e.equate(t,a),!0}]),0<=g(t,'InverseFunctionalProperty')&&(this.classActions['<'+v+'InverseFunctionalProperty>']=[function(e,t,n,a,r){return e.newPropertyAction(t,h)}]),0<=g(t,'FunctionalProperty')&&(this.classActions['<'+v+'FunctionalProperty>']=[function(e,t,n,a,r){return e.newPropertyAction(t,c)}])}},{key:'add',value:function e(n,a,r,o){var s;if(1===arguments.length){if(n instanceof Array)for(s=0;ss;s++){var c=this.index[s],f=u[s];c[f]||(c[f]=[]),c[f].push(d)}return this.statements.push(d),d}},{key:'addAll',value:function e(t){var n=this;t.forEach(function(e){n.add(e.subject,e.predicate,e.object,e.graph)})}},{key:'any',value:function e(t,n,a,r){var o=this.anyStatementMatching(t,n,a,r);if(null!=o)return null==t?o.subject:null==n?o.predicate:null==a?o.object:void 0}},{key:'anyValue',value:function e(t,n,a,r){var o=this.any(t,n,a,r);return o?o.value:void 0}},{key:'anyStatementMatching',value:function e(t,n,a,r){var o=this.statementsMatching(t,n,a,r,!0);return o&&0!==o.length?o[0]:void 0}},{key:'canon',value:function e(t){if(!t)return t;var n=this.redirections[t.hashString()];return n?n:t}},{key:'check',value:function e(){this.checkStatementList(this.statements);for(var t=0,n;4>t;t++)for(var a in n=this.index[t],n)n.hasOwnProperty(a)&&this.checkStatementList(n[a],t)}},{key:'checkStatementList',value:function e(t,n){for(var a=['subject','predicate','object','why'],r=' found in '+a[n]+' index.',o=0,i;ol;l++){var p=this.canon(s[l]),u=p.hashString();this.index[l][u]&&d(this.index[l][u],i)}if(!d(this.statements,i))throw new Error('Statement list does not statement '+i+'@'+i.why+r)}}},{key:'close',value:function e(){return this}},{key:'copyTo',value:function e(t,n,a){a||(a=[]);var r=this.statementsMatching(t);-1!==g(a,'two-direction')&&r.concat(this.statementsMatching(void 0,void 0,t));for(var o=0,i;oa?this.replaceWith(n,t):this.replaceWith(t,n))}},{key:'formula',value:function e(n){return new t(n)}},{key:'match',value:function e(t,n,a,r){return this.statementsMatching(x.fromValue(t),x.fromValue(n),x.fromValue(a),x.fromValue(r))}},{key:'mentionsURI',value:function e(t){var n='<'+t+'>';return!!this.subjectIndex[n]||!!this.objectIndex[n]||!!this.predicateIndex[n]}},{key:'newExistential',value:function e(t){if(!t)return this.bnode();var n=this.sym(t);return this.declareExistential(n)}},{key:'newPropertyAction',value:function e(t,n){var a=t.hashString();this.propertyActions[a]||(this.propertyActions[a]=[]),this.propertyActions[a].push(n);for(var r=this.statementsMatching(void 0,t,void 0),o=!1,s=0;sa;a++){var r=this.canon(n[a]),o=r.hashString();this.index[a][o]&&y(this.index[a][o],t)}return y(this.statements,t),this}},{key:'removeStatements',value:function e(t){for(var n=0;ns;s++)o(this.index[s]);if(this.redirections[a]=n,t.uri){if(this.aliases[r]||(this.aliases[r]=[]),this.aliases[r].push(t),this.aliases[a])for(s=0;sh;h++)d[h]=this.canon(x.fromValue(s[h])),d[h]?(c.push(h),l[h]=d[h].hashString()):u.push(h);if(0===c.length)return this.statements;if(1===c.length)return h=c[0],p=this.index[h][l[h]],p&&o&&1 '+t[a]);return n},i=function e(t){var a='Bindings: ',r=t.length,n;for(n=0;ne)return this.originalCallback(t);for(n=0;nd;d++){var p=o[d];if(p.uri&&p.uri===l);else if(p.isVar&&void 0===r[p])a.nvars++;else{if(p=c(o[d],r),n.redirections[p.hashString()]&&(p=n.redirections[p.hashString()]),s=i[d][p.hashString()],!s)return a.index=[],!1;(null===a.index||a.index.length>s.length)&&(a.index=s)}}return null===a.index&&(a.index=n.statements),!0},x=0,_=function e(a,r,l,p,u,c,h){s.debug('Match begins, Branch count now: '+h.count+' for '+h.pattern_debug);var f=a.fetcher?a.fetcher:null,g=r.statements;if(0===g.length){if(s.debug('FOUND MATCH WITH BINDINGS:'+o(l)),0===r.optional.length)h.reportMatch(l);else{s.debug('OPTIONAL: '+r.optional);var _=new m(t,l),w=[],k;for(k=0;k in query: '+o),e(a,r,l,p,u,c,h)})};for(T=0;T: Bad syntax: '+r+'\nat: "'+w(n,a,a+30)+'"'}function u(e){var t='',n=new T(e);try{for(;!0;){var a=n.next();if('\r'!=a)var t=t+a}}catch(t){if(t!=k)throw t}return t}function c(e){}var h=String.prototype,f={encode:function e(t){t=t.replace(/\r\n/g,'\n');for(var a='',o=0,n;on?a+=r(n):127n?(a+=r(192|n>>6),a+=r(128|63&n)):(a+=r(224|n>>12),a+=r(128|63&n>>6),a+=r(128|63&n));return a},decode:function e(t){for(var n='',a=0,o;ao?(n+=r(o),a++):191o?(n+=r((31&o)<<6|63&t.charCodeAt(a+1)),a+=2):(n+=r((15&o)<<12|(63&t.charCodeAt(a+1))<<6|63&t.charCodeAt(a+2)),a+=3);return n}},g='http://www.w3.org/2000/10/swap/log#forSome',m='http://www.w3.org/2000/10/swap/log#forAll',y='http://www.w3.org/2000/10/swap/log#',b=function e(t){return t},_=function e(t){return t},x=function e(t){if(0?@[\\]^`{|}~',W=X+':',J='http://www.w3.org/1999/02/22-rdf-syntax-ns#',Y='#',Q=/^[ \t]*(#[^\n]*)?\r?\n/g,G=/^[ \t]*(#[^\n]*)?$/g,K=/^[ \t]*/g,Z=/^[-+]?[0-9]+/g,ee=/^([-+]?[0-9]+)(\.[0-9]+)?(e[-+]?[0-9]+)?/g,te=/^[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?/,ne=/^[0-9]+/g,ae=/[\\\r\n\"]/g,re=/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*/g;return i.prototype.here=function(e){return this._genPrefix+'_L'+this.lines+'C'+(e-this.startOfLine+1)},i.prototype.formula=function(){return this._formula},i.prototype.loadStream=function(e){return this.loadBuf(e.read())},i.prototype.loadBuf=function(e){return this.startDoc(),this.feed(e),this.endDoc()},i.prototype.feed=function(e){for(var t=e.decode('utf-8'),n=0,a;0<=n;){if(a=this.skipSpace(t,n),0>a)return;var n=this.directiveOrStatement(t,a);if(0>n)throw p(this._thisDoc,this.lines,t,a,'expected directive or statement')}},i.prototype.directiveOrStatement=function(e,t){var n=this.skipSpace(e,t);if(0>n)return n;var a=this.directive(e,n);if(0<=a)return this.checkDot(e,a);var a=this.statement(e,n);return 0<=a?this.checkDot(e,a):a},i.prototype.tok=function(e,t,n){var a='\t\n\x0B\f\r ';if('@'==w(t,n,n+1))var n=n+1;else if(0>s(this.keywords,e))return-1;var r=n+v(e);return w(t,n,r)==e&&0<=X.indexOf(t.charAt(r))?r:-1},i.prototype.directive=function(n,a){var r=this.skipSpace(n,a);if(0>r)return r;var o=new _([]),r=this.tok('bind',n,a);if(0a)throw p(this._thisDoc,this.lines,n,a,'\'@keywords\' needs comma separated list of words');return this.setKeywords(w(o,null,null)),80a)throw p(this._thisDoc,this.lines,n,a,'Bad variable list after @forAll');var i=new T(o);try{for(;!0;){var d=i.next();(0>s(this._variables,d)||0<=s(this._parentVariables,d))&&(this._variables[d]=this._context.newUniversal(d))}}catch(t){if(t!=k)throw t}return a}var r=this.tok('forSome',n,a);if(0a)throw p(this._thisDoc,this.lines,n,a,'Bad variable list after @forSome');var i=new T(o);try{for(;!0;){var d=i.next();this._context.declareExistential(d)}}catch(t){if(t!=k)throw t}return a}var r=this.tok('prefix',n,a);if(0<=r){var l=new _([]),a=this.qname(n,r,l);if(0>a)throw p(this._thisDoc,this.lines,n,r,'expected qname after @prefix');var r=this.uri_ref2(n,a,l);if(0>r)throw p(this._thisDoc,this.lines,n,a,'expected after @prefix _qname_');var t=l[1].uri;if(this._baseURI)var t=C(this._baseURI,t);else S(0<=t.indexOf(':'),'With no base URI, cannot handle relative URI for NS');return S(0<=t.indexOf(':')),this._bindings[l[0][0]]=t,this.bind(l[0][0],e(t)),r}var r=this.tok('base',n,a);if(0<=r){var l=new _([]),a=this.uri_ref2(n,r,l);if(0>a)throw p(this._thisDoc,this.lines,n,r,'expected after @base ');var t=l[0].uri;if(this._baseURI)var t=C(this._baseURI,t);else throw p(this._thisDoc,this.lines,n,r,'With no previous base URI, cannot use relative URI in @base <'+t+'>');return S(0<=t.indexOf(':')),this._baseURI=t,a}return-1},i.prototype.bind=function(e,t){''==e||this._store.setPrefixForURI(e,t)},i.prototype.setKeywords=function(e){null==e?this.keywordsSet=0:(this.keywords=e,this.keywordsSet=1)},i.prototype.startDoc=function(){},i.prototype.endDoc=function(){return this._formula},i.prototype.makeStatement=function(e){e[0].add(e[2],e[1],e[3],this.source),this.statementCount+=1},i.prototype.statement=function(e,t){var n=new _([]),t=this.object(e,t,n);if(0>t)return t;var a=this.property_list(e,t,n[0]);if(0>a)throw p(this._thisDoc,this.lines,e,t,'expected propertylist');return a},i.prototype.subject=function(e,t,n){return this.item(e,t,n)},i.prototype.verb=function(e,t,n){var a=this.skipSpace(e,t);if(0>a)return a;var o=new _([]),a=this.tok('has',e,t);if(0<=a){var t=this.prop(e,a,o);if(0>t)throw p(this._thisDoc,this.lines,e,a,'expected property after \'has\'');return n.push(new b(['->',o[0]])),t}var a=this.tok('is',e,t);if(0<=a){var t=this.prop(e,a,o);if(0>t)throw p(this._thisDoc,this.lines,e,a,'expected after \'is\'');var a=this.skipSpace(e,t);if(0>a){throw p(this._thisDoc,this.lines,e,t,'End of file found, expected property after \'is\'');return a}var t=a,a=this.tok('of',e,t);if(0>a)throw p(this._thisDoc,this.lines,e,t,'expected \'of\' after \'is\' ');return n.push(new b(['<-',o[0]])),a}var a=this.tok('a',e,t);if(0<=a)return n.push(new b(['->',this._store.sym(D)])),a;if('<='==w(e,t,t+2))return n.push(new b(['<-',this._store.sym(y+'implies')])),t+2;if('='==w(e,t,t+1))return'>'==w(e,t+1,t+2)?(n.push(new b(['->',this._store.sym(y+'implies')])),t+2):(n.push(new b(['->',this._store.sym(U)])),t+1);if(':='==w(e,t,t+2))return n.push(new b(['->',y+'becomes'])),t+2;var a=this.prop(e,t,o);if(0<=a)return n.push(new b(['->',o[0]])),a;if('>-'==w(e,t,t+2)||'<-'==w(e,t,t+2))throw p(this._thisDoc,this.lines,e,a,'>- ... -> syntax is obsolete.');return-1},i.prototype.prop=function(e,t,n){return this.item(e,t,n)},i.prototype.item=function(e,t,n){return this.path(e,t,n)},i.prototype.blankNode=function(e){return this._context.bnode(e,this._reason2)},i.prototype.path=function(e,t,n){var a=this.nodeOrLiteral(e,t,n);if(0>a)return a;for(;0<='!^.'.indexOf(w(e,a,a+1));){var r=w(e,a,a+1);if('.'==r){var o=w(e,a+1,a+2);if(!o||0<=W.indexOf(o)&&0>':?<[{('.indexOf(o))break}var i=n.pop(),s=this.blankNode(this.here(a)),a=this.node(e,a+1,n);if(0>a)throw p(this._thisDoc,this.lines,e,a,'EOF found in middle of path syntax');var d=n.pop();'^'==r?this.makeStatement(new b([this._context,d,s,i])):this.makeStatement(new b([this._context,d,i,s])),n.push(s)}return a},i.prototype.anonymousNode=function(e){var t=this._anonymousNodes[e];if(t)return t;var t=this._store.bnode(e);return this._anonymousNodes[e]=t,t},i.prototype.node=function(e,t,n,a){'undefined'==typeof a&&(a=null);var r=a,o=this.skipSpace(e,t);if(0>o)return o;var t=o,i=w(e,t,t+1);if('['==i){var s=this.here(t),o=this.skipSpace(e,t+1);if(0>o)throw p(this._thisDoc,this.lines,e,t,'EOF after \'[\'');if('='==w(e,o,o+1)){var t=o+1,d=new _([]),o=this.objectList(e,t,d);if(0<=o){var r=d[0];if(1o)throw p(this._thisDoc,this.lines,e,t,'EOF when objectList expected after [ = ');if(';'==w(e,o,o+1))var o=o+1}else throw p(this._thisDoc,this.lines,e,t,'objectList expected after [= ')}if(null==r)var r=this.blankNode(s);var t=this.property_list(e,o,r);if(0>t)throw p(this._thisDoc,this.lines,e,o,'property_list expected');var o=this.skipSpace(e,t);if(0>o)throw p(this._thisDoc,this.lines,e,t,'EOF when \']\' expected after [ ');if(']'!=w(e,o,o+1))throw p(this._thisDoc,this.lines,e,o,'\']\' expected');return n.push(r),o+1}if('{'==i){var c=w(e,t+1,t+2);if('$'==c){t+=1;for(var o=t+1,h=new _([]),f=!0,t;1;){if(t=this.skipSpace(e,o),0>t)throw p(this._thisDoc,this.lines,e,t,'needed \'$}\', found end.');if('$}'==w(e,t,t+2)){var o=t+2;break}if(!!f)var f=!1;else if(','==w(e,t,t+1))t+=1;else throw p(this._thisDoc,this.lines,e,t,'expected: \',\'');var g=new _([]),o=this.item(e,t,g);if(0>o)throw p(this._thisDoc,this.lines,e,t,'expected item in set or \'$}\'');h.push(g[0])}return n.push(this._store.newSet(h,this._context)),o}var o=t+1,m=this._parentContext;this._parentContext=this._context;var y=this._anonymousNodes,N=this._parentVariables;this._parentVariables=this._variables,this._anonymousNodes=new x([]),this._variables=this._variables.slice();var I=this._reason2;if(this._reason2=L,null==r)var r=this._store.formula();for(this._context=r;1;){var t=this.skipSpace(e,o);if(0>t)throw p(this._thisDoc,this.lines,e,t,'needed \'}\', found end.');if('}'==w(e,t,t+1)){var o=t+1;break}var o=this.directiveOrStatement(e,t);if(0>o)throw p(this._thisDoc,this.lines,e,t,'expected statement or \'}\'')}return this._anonymousNodes=y,this._variables=this._parentVariables,this._parentVariables=N,this._context=this._parentContext,this._reason2=I,this._parentContext=m,n.push(r.close()),o}if('('==i){var S=this._store.list,c=w(e,t+1,t+2);if('$'==c){var S=this._store.newSet;t+=1}for(var o=t+1,h=new _([]),t;1;){if(t=this.skipSpace(e,o),0>t)throw p(this._thisDoc,this.lines,e,t,'needed \')\', found end.');if(')'==w(e,t,t+1)){var o=t+1;break}var g=new _([]),o=this.item(e,t,g);if(0>o)throw p(this._thisDoc,this.lines,e,t,'expected item in list or \')\'');h.push(g[0])}return n.push(S(h,this._context)),o}var o=this.tok('this',e,t);if(0<=o){throw p(this._thisDoc,this.lines,e,t,'Keyword \'this\' was ancient N3. Now use @forSome and @forAll keywords.');return n.push(this._context),o}var o=this.tok('true',e,t);if(0<=o)return n.push(!0),o;var o=this.tok('false',e,t);if(0<=o)return n.push(!1),o;if(null==r){var o=this.uri_ref2(e,t,n);if(0<=o)return o}return-1},i.prototype.property_list=function(e,t,n){for(;1;){var a=this.skipSpace(e,t);if(0>a){throw p(this._thisDoc,this.lines,e,t,'EOF found when expected verb in property list');return a}if(':-'==w(e,a,a+2)){var t=a+2,r=new _([]),a=this.node(e,t,r,n);if(0>a)throw p(this._thisDoc,this.lines,e,t,'bad {} or () or [] node after :- ');var t=a;continue}var t=a,o=new _([]),a=this.verb(e,t,o);if(0>=a)return t;var i=new _([]),t=this.objectList(e,a,i);if(0>t)throw p(this._thisDoc,this.lines,e,a,'objectList expected');var s=new T(i);try{for(;!0;){var d=s.next(),l=o[0],u=l[0],c=l[1];'->'==u?this.makeStatement(new b([this._context,c,n,d])):this.makeStatement(new b([this._context,c,d,n]))}}catch(t){if(t!=k)throw t}var a=this.skipSpace(e,t);if(0>a){throw p(this._thisDoc,this.lines,e,a,'EOF found in list of objects');return a}if(';'!=w(e,t,t+1))return t;var t=t+1}},i.prototype.commaSeparatedList=function(e,t,n,a){var r=this.skipSpace(e,t);if(0>r){throw p(this._thisDoc,this.lines,e,r,'EOF found expecting comma sep list');return r}if('.'==e.charAt(r))return t;if(a)var r=this.uri_ref2(e,r,n);else var r=this.bareWord(e,r,n);if(0>r)return-1;for(;1;){var t=this.skipSpace(e,r);if(0>t)return t;var o=w(e,t,t+1);if(','!=o)return'.'==o?t:-1;if(a)var r=this.uri_ref2(e,t+1,n);else var r=this.bareWord(e,t+1,n);if(0>r){throw p(this._thisDoc,this.lines,e,r,'bad list content');return r}}},i.prototype.objectList=function(e,t,n){var t=this.object(e,t,n);if(0>t)return-1;for(;1;){var a=this.skipSpace(e,t);if(0>a){throw p(this._thisDoc,this.lines,e,a,'EOF found after object');return a}if(','!=w(e,a,a+1))return a;var t=this.object(e,a+1,n);if(0>t)return t}},i.prototype.checkDot=function(e,t){var n=this.skipSpace(e,t);if(0>n)return n;if('.'==w(e,n,n+1))return n+1;if('}'==w(e,n,n+1))return n;if(']'==w(e,n,n+1))return n;throw p(this._thisDoc,this.lines,e,n,'expected \'.\' or \'}\' or \']\' at end of statement');return t},i.prototype.uri_ref2=function(e,t,n){var a=new _([]),r=this.qname(e,t,a);if(0<=r){var o=a[0],i=o[0],d=o[1];if(null==i){S(0,'not used?');var l=this._baseURI+A}else{var l=this._bindings[i];if(!l){if('_'==i)return n.push(this.anonymousNode(d)),r;throw p(this._thisDoc,this.lines,e,t,'Prefix '+i+' not bound.')}}var u=this._store.sym(l+d);return 0<=s(this._variables,u)?n.push(this._variables[u]):n.push(u),r}var t=this.skipSpace(e,t);if(0>t)return-1;if('?'==e.charAt(t)){var c=new _([]),r=this.variable(e,t,c);return 0'==e.charAt(t)){var f=w(e,h,t);if(this._baseURI)var f=C(this._baseURI,f);else S(0<=f.indexOf(':'),'With no base URI, cannot deal with relative URIs');if('#'==w(e,t-1,t)&&'#'!=w(f,-1,null))var f=f+'#';var u=this._store.sym(f);return 0<=s(this._variables,u)?n.push(this._variables[u]):n.push(u),t+1}var t=t+1}throw p(this._thisDoc,this.lines,e,r,'unterminated URI reference')}else{if(this.keywordsSet){var c=new _([]),r=this.bareWord(e,t,c);if(0>r)return-1;if(0<=s(this.keywords,c[0]))throw p(this._thisDoc,this.lines,e,t,'Keyword "'+c[0]+'" not allowed here.');return n.push(this._store.sym(this._bindings['']+c[0])),r}return-1}},i.prototype.skipSpace=function(e,t){for(var n=' \n\r\t\f\x0B\xA0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u3000',a=t?t:0,r;an.indexOf(r)))'\n'===e.charAt(a)&&++this.lines;else if('#'===e.charAt(a)){for(;;a++){if(a===e.length)return-1;if('\n'===e.charAt(a)){++this.lines;break}};}else return a;return-1},i.prototype.variable=function(e,t,n){var a=this.skipSpace(e,t);if(0>a)return-1;if('?'!=w(e,a,a+1))return-1;var a=a+1,t=a;if(0<='0123456789-'.indexOf(e.charAt(a))){throw p(this._thisDoc,this.lines,e,a,'Varible name can\'t start with \''+e.charAt(a)+'s\'');return-1}for(;tW.indexOf(e.charAt(t));)var t=t+1;if(null==this._parentContext)throw p(this._thisDoc,this.lines,e,a,'Can\'t use ?xxx syntax for variable in outermost level: '+w(e,a-1,t));return n.push(this._store.variable(w(e,a,t))),t},i.prototype.bareWord=function(e,t,n){var a=this.skipSpace(e,t);if(0>a)return-1;var r=e.charAt(a);if(0<='0123456789-'.indexOf(r))return-1;if(0<=W.indexOf(r))return-1;for(var t=a,t;tW.indexOf(e.charAt(t));)++t;return n.push(w(e,a,t)),t},i.prototype.qname=function(e,t,n){var t=this.skipSpace(e,t);if(0>t)return-1;var a=e.charAt(t);if(0<='0123456789-+'.indexOf(a))return-1;if(0>W.indexOf(a))for(var r=a,t=t+1,a;tW.indexOf(a));)var r=r+a,t=t+1;else var r='';if(tW.indexOf(a));)var r=r+a,t=t+1;return n.push(new b([o,r])),t}return r&&this.keywordsSet&&0>s(this.keywords,r)?(n.push(new b(['',r])),t):-1},i.prototype.object=function(e,t,n){var a=this.subject(e,t,n);if(0<=a)return a;var a=this.skipSpace(e,t);if(0>a)return-1;var t=a,r=null,o=e.charAt(t);if('"'==o||'\''==o){r=e.slice(t,t+3==o+o)?o+o+o:o;var t=t+v(r),i=this.strconst(e,t,r),a=i[0],d=i[1];return n.push(this._store.literal(d)),E('New string const ',d,a),a}return-1},i.prototype.nodeOrLiteral=function(e,t,n){var a=this.node(e,t,n);if(0<=a)return a;var a=this.skipSpace(e,t);if(0>a)return-1;var t=a,r=e.charAt(t);if(0<='-+0987654321'.indexOf(r)){te.lastIndex=0;var o=te.exec(e.slice(t));if(null!=o){var i=o[0];a=t+i.length,0<=i.indexOf('T')?n.push(this._store.literal(i,void 0,this._store.sym(H))):n.push(this._store.literal(i,void 0,this._store.sym(q)))}else{ee.lastIndex=0;var o=ee.exec(e.slice(t));if(null==o)throw p(this._thisDoc,this.lines,e,t,'Bad number or date syntax');a=t+ee.lastIndex;var i=w(e,t,a);0<=i.indexOf('e')?n.push(this._store.literal(parseFloat(i),void 0,this._store.sym(F))):0<=w(e,t,a).indexOf('.')?n.push(this._store.literal(parseFloat(i),void 0,this._store.sym(B))):n.push(this._store.literal(parseInt(i),void 0,this._store.sym(M)))};return a}if('"'==e.charAt(t)){if('"""'==w(e,t,t+3))var d='"""';else var d='"';var t=t+v(d),l=null,u=this.strconst(e,t,d),a=u[0],c=u[1],s=null;if('@'==w(e,a,a+1)){re.lastIndex=0;var o=re.exec(e.slice(a+1));if(null==o)throw p(this._thisDoc,startline,e,t,'Bad language code syntax on string literal, after @');var t=re.lastIndex+a+1,s=w(e,a+1,t),a=t}if('^^'==w(e,a,a+2))var h=new _([]),a=this.uri_ref2(e,a+2,h),l=h[0];return n.push(this._store.literal(c,s,l)),a}return-1},i.prototype.strconst=function(e,t,n){for(var a=t,r='',o=this.lines,t;ao;){var s=w(e,a,a+1),d=s.toLowerCase(),a=a+1;if(''==d)throw p(this._thisDoc,n,e,t,'unterminated string literal(3)');var l=I('0123456789abcdef',d);if(0>l)throw p(this._thisDoc,n,e,t,'bad string literal hex escape');var i=16*i+l,o=o+1}var u=r(i);return new b([a,u])},i.prototype.UEscape=function(e,t,n){for(var a=t,r=0,o='\\U';8>r;){var i=w(e,a,a+1),s=i.toLowerCase(),a=a+1;if(''==s)throw p(this._thisDoc,n,e,t,'unterminated string literal(3)');var d=I('0123456789abcdef',s);if(0>d)throw p(this._thisDoc,n,e,t,'bad string literal hex escape');var o=o+s,r=r+1}var l=R('0x'+w(o,2,10)-0);return new b([a,l])},l.prototype.toString=function(){var e=this._str,t=this._i,n=0;if(60: Bad syntax (%s) at ^ in:\n"%s%s^%s%s"'%new b([this.lines+1,this._uri,this._why,a,w(e,n,t),w(e,t,t+60),r])},n}();e.exports=i},function(e,t,n){(function(t){function n(e){if(!(this instanceof n))return new n(e);if(e&&e.lineMode){this._tripleQuotedString=this._number=this._boolean=/$0^/;var t=this;this._tokenize=this.tokenize,this.tokenize=function(e,n){this._tokenize(e,function(e,a){!e&&/^(?:IRI|prefixed|literal|langcode|type|\.|eof)$/.test(a.type)?n&&n(e,a):n&&n(e||t._syntaxError(a.type,n=null))})}}}var a=r,o='function'==typeof t?t:function e(t){setTimeout(t,0)},i=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\[uU]|\\(.)/g,s={"\\":'\\',"'":'\'','"':'"',n:'\n',r:'\r',t:'\t',f:'\f',b:'\b',_:'_',"~":'~',".":'.',"-":'-',"!":'!',$:'$',"&":'&',"(":'(',")":')',"*":'*',"+":'+',",":',',";":';',"=":'=',"/":'/',"?":'?',"#":'#',"@":'@',"%":'%'},d=/[\x00-\x20<>\\"\{\}\|\^\`]/;n.prototype={_iri:/^<((?:[^>\\]|\\[uU])+)>/,_unescapedIri:/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>/,_unescapedString:/^"[^"\\]+"(?=[^"\\])/,_singleQuotedString:/^"[^"\\]*(?:\\.[^"\\]*)*"(?=[^"\\])|^'[^'\\]*(?:\\.[^'\\]*)*'(?=[^'\\])/,_tripleQuotedString:/^""("[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*")""|^''('[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*')''/,_langcode:/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,_prefix:/^((?:[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]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,_prefixed:/^((?:[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]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-: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]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?=\.?[,;\s#()\[\]\{\}"'<])/,_blank:/^_:((?:[0-9A-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]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=\.?[,;:\s#()\[\]\{\}"'<])/,_number:/^[\-+]?(?:\d+\.?\d*([eE](?:[\-\+])?\d+)|\d*\.?\d+)(?=[.,;:\s#()\[\]\{\}"'<])/,_boolean:/^(?:true|false)(?=[.,;:\s#()\[\]\{\}"'<])/,_keyword:/^@[a-z]+(?=[\s#<:])/,_sparqlKeyword:/^(?:PREFIX|BASE|GRAPH)(?=[\s#<:])/i,_shortPredicates:/^a(?=\s+|<)/,_newline:/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,_whitespace:/^[ \t]+/,_endOfFile:/^(?:#[^\n\r]*)?$/,_tokenizeToEnd:function(e,t){function n(t){e(t._syntaxError(/^\S*/.exec(a)[0]))}for(var a=this._input;!0;){for(var r;r=this._newline.exec(a);)a=a.substr(r[0].length,a.length),this._line++;if((r=this._whitespace.exec(a))&&(a=a.substr(r[0].length,a.length)),this._endOfFile.test(a))return t&&e(a=null,{line:this._line,type:'eof',value:'',prefix:''}),this._input=a;var o=this._line,i='',s='',l='',p=a[0],u=null,c=0,h=!1,f;switch(p){case'^':if(1===a.length)break;else if('^'!==a[1])return n(this);if(this._prevTokenType='^',a=a.substr(2),'<'!==a[0]){h=!0;break}case'<':if(u=this._unescapedIri.exec(a))i='IRI',s=u[1];else if(u=this._iri.exec(a)){if(f=this._unescape(u[1]),null===f||d.test(f))return n(this);i='IRI',s=f}break;case'_':((u=this._blank.exec(a))||t&&(u=this._blank.exec(a+' ')))&&(i='prefixed',l='_',s=u[1]);break;case'"':case'\'':if(u=this._unescapedString.exec(a))i='literal',s=u[0];else if(u=this._singleQuotedString.exec(a)){if(f=this._unescape(u[0]),null===f)return n(this);i='literal',s=f.replace(/^'|'$/g,'"')}else if(u=this._tripleQuotedString.exec(a)){if(f=u[1]||u[2],this._line+=f.split(/\r\n|\r|\n/).length-1,f=this._unescape(f),null===f)return n(this);i='literal',s=f.replace(/^'|'$/g,'"')}break;case'@':'literal'===this._prevTokenType&&(u=this._langcode.exec(a))?(i='langcode',s=u[1]):(u=this._keyword.exec(a))&&(i=u[0]);break;case'.':if(1===a.length?t:'0'>a[1]||'9'=o?a(o):a(55296+(o-=65536)/1024,56320+(1023&o))}var i=s[r];if(!i)throw new Error;return i})}catch(e){return null}},_syntaxError:function(e){return this._input=null,new Error('Syntax error: unexpected "'+e+'" on line '+this._line+'.')},tokenize:function(e,t){function n(e){null!==r._input&&(r._input+=e,r._tokenizeToEnd(t,!1))}function a(){null!==r._input&&r._tokenizeToEnd(t,!0)}var r=this;this._line=1,'string'==typeof e?(this._input=e,o(function(){r._tokenizeToEnd(t,!0)})):(this._input='',e&&'function'!=typeof e?('function'==typeof e.setEncoding&&e.setEncoding('utf8'),e.on('data',n),e.on('end',a)):(this.addChunk=n,this.end=a,!t&&(t=e)))}},e.exports=n}).call(this,n(13).setImmediate)},function(e,t,n){function a(e){if(!(this instanceof a))return new a(e);this._tripleStack=[],this._graph=null,e=e||{},this._setBase(e.documentIRI);var t='string'==typeof e.format&&e.format.match(/\w*$/)[0].toLowerCase(),n='turtle'===t,i='trig'===t,s=/triple/.test(t),d=/quad/.test(t),l=s||d;(this._supportsNamedGraphs=!n)||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(n||i||s),l&&(this._base='',this._resolveIRI=function(e){return this._error('Disallowed relative IRI',e),this._callback=r,this._subject=null}),this._blankNodePrefix='string'==typeof e.blankNodePrefix?'_:'+e.blankNodePrefix.replace(/^_:/,''):'',this._lexer=e.lexer||new o({lineMode:l})}function r(){}var o=n(25),i='http://www.w3.org/1999/02/22-rdf-syntax-ns#',s=i+'nil',d=i+'first',l=i+'rest',p=/^[a-z][a-z0-9+.-]*:/i,u=/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i,c=/(?:^|\/)\.\.?(?:$|[\/#?])/,h=0,f=0;a._resetBlankNodeIds=function(){h=f=0},a.prototype={_setBase:function(e){if(!e)e=null;else if(0<=e.indexOf('#'))throw new Error('Invalid base IRI '+e);(this._base=e)&&(this._basePath=e.replace(/[^\/?]*(?:\?.*)?$/,''),e=e.match(u),this._baseRoot=e[0],this._baseScheme=e[1])},_readInTopContext:function(e){switch(e.type){case'eof':return null===this._graph?(delete this._prefixes._,this._callback(null,null,this._prefixes)):this._error('Unclosed graph',e);case'@prefix':return this._sparqlStyle=!1,this._readPrefix;case'PREFIX':return this._sparqlStyle=!0,this._readPrefix;case'@base':return this._sparqlStyle=!1,this._readBaseIRI;case'BASE':return this._sparqlStyle=!0,this._readBaseIRI;case'{':if(this._supportsNamedGraphs)return this._graph='',this._subject=null,this._readSubject;case'GRAPH':if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e);}},_readSubject:function(e){switch(this._predicate=null,e.type){case'IRI':this._subject=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e);break;case'prefixed':var t=this._prefixes[e.prefix];if(void 0===t)return this._error('Undefined prefix "'+e.prefix+':"',e);this._subject=t+e.value;break;case'[':return this._subject='_:b'+f++,this._tripleStack.push({subject:this._subject,predicate:null,object:null,type:'blank'}),this._readBlankNodeHead;case'(':return this._tripleStack.push({subject:s,predicate:null,object:null,type:'list'}),this._subject=null,this._readListItem;case'}':return this._readPunctuation(e);default:return this._error('Expected subject but got '+e.type,e);}return this._readPredicateOrNamedGraph},_readPredicate:function(e){var t=e.type;switch(t){case'IRI':case'abbreviation':this._predicate=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e);break;case'prefixed':if('_'===e.prefix)return this._error('Disallowed blank node as predicate',e);var n=this._prefixes[e.prefix];if(void 0===n)return this._error('Undefined prefix "'+e.prefix+':"',e);this._predicate=n+e.value;break;case'.':case']':case'}':return null===this._predicate?this._error('Unexpected '+t,e):(this._subject=null,']'===t?this._readBlankNodeTail(e):this._readPunctuation(e));case';':return this._readPredicate;default:return this._error('Expected predicate to follow "'+this._subject+'"',e);}return this._readObject},_readObject:function(e){switch(e.type){case'IRI':this._object=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e);break;case'prefixed':var t=this._prefixes[e.prefix];if(void 0===t)return this._error('Undefined prefix "'+e.prefix+':"',e);this._object=t+e.value;break;case'literal':return this._object=e.value,this._readDataTypeOrLang;case'[':var n='_:b'+f++;return this._tripleStack.push({subject:this._subject,predicate:this._predicate,object:n,type:'blank'}),this._subject=n,this._readBlankNodeHead;case'(':return this._tripleStack.push({subject:this._subject,predicate:this._predicate,object:s,type:'list'}),this._subject=null,this._readListItem;default:return this._error('Expected object to follow "'+this._predicate+'"',e);}return this._getTripleEndReader()},_readPredicateOrNamedGraph:function(e){return'{'===e.type?this._readGraph(e):this._readPredicate(e)},_readGraph:function(e){return'{'===e.type?(this._graph=this._subject,this._subject=null,this._readSubject):this._error('Expected graph but got '+e.type,e)},_readBlankNodeHead:function(e){return']'===e.type?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))},_readBlankNodeTail:function(e){if(']'!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._callback(null,{subject:this._subject,predicate:this._predicate,object:this._object,graph:this._graph||''});var t=this._tripleStack.pop();return this._subject=t.subject,null===t.object?null===this._predicate?this._readPredicateOrNamedGraph:this._readPredicate:(this._predicate=t.predicate,this._object=t.object,this._getTripleEndReader())},_readDataTypeOrLang:function(e){switch(e.type){case'type':var t;if(''===e.prefix)t=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e);else{var n=this._prefixes[e.prefix];if(void 0===n)return this._error('Undefined prefix "'+e.prefix+':"',e);t=n+e.value}return this._object+='^^'+t,this._getTripleEndReader();case'langcode':return this._object+='@'+e.value.toLowerCase(),this._getTripleEndReader();default:return this._getTripleEndReader().call(this,e);}},_readListItem:function(e){var t=null,n=null,a=this._subject,r=this._tripleStack,o=r[r.length-1],i=this._readListItem;switch(e.type){case'IRI':t=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e);break;case'prefixed':var u=this._prefixes[e.prefix];if(void 0===u)return this._error('Undefined prefix "'+e.prefix+':"',e);t=u+e.value;break;case'literal':t=e.value,i=this._readDataTypeOrLang;break;case'[':n='_:b'+f++,t='_:b'+f++,r.push({subject:n,predicate:d,object:t,type:'blank'}),this._subject=t,i=this._readBlankNodeHead;break;case'(':n='_:b'+f++,r.push({subject:n,predicate:d,object:s,type:'list'}),this._subject=null,i=this._readListItem;break;case')':if(r.pop(),0!==r.length&&'list'===r[r.length-1].type&&this._callback(null,{subject:o.subject,predicate:o.predicate,object:o.object,graph:this._graph||''}),this._subject=o.subject,null===o.predicate){if(i=this._readPredicate,o.subject===s)return i;}else if(this._predicate=o.predicate,this._object=o.object,i=this._getTripleEndReader(),o.object===s)return i;n=s;break;default:return this._error('Expected list item instead of "'+e.type+'"',e);}return null===n&&(this._subject=n='_:b'+f++),null===a?o.object===s?o.object=n:o.subject=n:this._callback(null,{subject:a,predicate:l,object:n,graph:this._graph||''}),null!==t&&this._callback(null,{subject:n,predicate:d,object:t,graph:this._graph||''}),i},_readPunctuation:function(e){var t=this._subject,n=this._graph,a;switch(e.type){case'}':if(null===this._graph)return this._error('Unexpected graph closing',e);this._graph=null;case'.':this._subject=null,a=this._readInTopContext;break;case';':a=this._readPredicate;break;case',':a=this._readObject;break;case'IRI':if(this._supportsQuads&&null===this._graph){n=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e),t=this._subject,a=this._readQuadPunctuation;break}case'prefixed':if(this._supportsQuads&&null===this._graph){var r=this._prefixes[e.prefix];if(void 0===r)return this._error('Undefined prefix "'+e.prefix+':"',e);n=r+e.value,a=this._readQuadPunctuation;break}default:return this._error('Expected punctuation to follow "'+this._object+'"',e);}return null!==t&&this._callback(null,{subject:t,predicate:this._predicate,object:this._object,graph:n||''}),a},_readBlankNodePunctuation:function(e){var t;switch(e.type){case';':t=this._readPredicate;break;case',':t=this._readObject;break;default:return this._error('Expected punctuation to follow "'+this._object+'"',e);}return this._callback(null,{subject:this._subject,predicate:this._predicate,object:this._object,graph:this._graph||''}),t},_readQuadPunctuation:function(e){return'.'===e.type?this._readInTopContext:this._error('Expected dot to follow quad',e)},_readPrefix:function(e){return'prefix'===e.type?(this._prefix=e.value,this._readPrefixIRI):this._error('Expected prefix to follow @prefix',e)},_readPrefixIRI:function(e){if('IRI'!==e.type)return this._error('Expected IRI to follow prefix "'+this._prefix+':"',e);var t;return t=null===this._base||p.test(e.value)?e.value:this._resolveIRI(e),this._prefixes[this._prefix]=t,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation},_readBaseIRI:function(e){if('IRI'!==e.type)return this._error('Expected IRI to follow base declaration',e);try{this._setBase(null===this._base||p.test(e.value)?e.value:this._resolveIRI(e))}catch(t){this._error(t.message,e)}return this._readDeclarationPunctuation},_readNamedGraphLabel:function(e){switch(e.type){case'IRI':case'prefixed':return this._readSubject(e),this._readGraph;case'[':return this._readNamedGraphBlankLabel;default:return this._error('Invalid graph label',e);}},_readNamedGraphBlankLabel:function(e){return']'===e.type?(this._subject='_:b'+f++,this._readGraph):this._error('Invalid graph label',e)},_readDeclarationPunctuation:function(e){return this._sparqlStyle?this._readInTopContext(e):'.'===e.type?this._readInTopContext:this._error('Expected declaration to end with a dot',e)},_getTripleEndReader:function(){var e=this._tripleStack;if(0===e.length)return this._readPunctuation;switch(e[e.length-1].type){case'blank':return this._readBlankNodeTail;case'list':return this._readListItem;}},_error:function(e,t){this._callback(new Error(e+' at line '+t.line+'.'))},_resolveIRI:function(e){var t=e.value;switch(t[0]){case void 0:return this._base;case'#':return this._base+t;case'?':return this._base.replace(/(?:\?.*)?$/,t);case'/':return('/'===t[1]?this._baseScheme:this._baseRoot)+this._removeDotSegments(t);default:return this._removeDotSegments(this._basePath+t);}},_removeDotSegments:function(e){if(!c.test(e))return e;for(var t='',n=e.length,a=-1,r=-1,o=0,i='/';ar&&'/'===e[++a]&&'/'===e[++a])for(;(r=a+1)=r&&(t=t.substr(0,o)),'/'!==i)return t+'/'+e.substr(a+1);o=a+1}}}i=e[++a]}return t+e.substring(o)},parse:function(e,t,n){this._readCallback=this._readInTopContext,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix||'_:b'+h++ +'_','function'==typeof e&&(n=t,t=e,e=null),this._callback=t||r,this._prefixCallback=n||r;var a=this;this._lexer.tokenize(e,function(e,t){null===e?a._readCallback!==void 0&&(a._readCallback=a._readCallback(t)):(a._callback(e),a._callback=r)}),e||(this.addChunk=this._lexer.addChunk,this.end=this._lexer.end)}},e.exports=a},function(e,t){function n(e,t){for(var n in p)t?e.prototype[n]=a(p[n]):e[n]=p[n];return e}function a(e){return function(t){return e(this,t)}}var r='http://www.w3.org/2001/XMLSchema#',o=r+'string',i=r+'integer',s=r+'decimal',d=r+'boolean',l='http://www.w3.org/1999/02/22-rdf-syntax-ns#langString',p={isIRI:function(e){if(!e)return e;var t=e[0];return'"'!==t&&'_'!==t},isLiteral:function(e){return e&&'"'===e[0]},isBlank:function(e){return e&&'_:'===e.substr(0,2)},getLiteralValue:function(e){var t=/^"([^]*)"/.exec(e);if(!t)throw new Error(e+' is not a literal');return t[1]},getLiteralType:function(e){var t=/^"[^]*"(?:\^\^([^"]+)|(@)[^@"]+)?$/.exec(e);if(!t)throw new Error(e+' is not a literal');return t[1]||(t[2]?l:o)},getLiteralLanguage:function(e){var t=/^"[^]*"(?:@([^@"]+)|\^\^[^"]+)?$/.exec(e);if(!t)throw new Error(e+' is not a literal');return t[1]?t[1].toLowerCase():''},isPrefixedName:function(e){return e&&/^[^:\/"']*:[^:\/"']+$/.test(e)},expandPrefixedName:function(e,t){var n=/(?:^|"\^\^)([^:\/#"'\^_]*):[^\/]*$/.exec(e),a,r,o;return n&&(a=n[1],r=t[a],o=n.index),void 0===r?e:0===o?r+e.substr(a.length+1):e.substr(0,o+3)+r+e.substr(o+a.length+4)},createIRI:function(e){return e&&'"'===e[0]?p.getLiteralValue(e):e},createLiteral:function(e,t){if(!t)switch(typeof e){case'boolean':t=d;break;case'number':if(isFinite(e)){t=0==e%1?i:s;break}default:return'"'+e+'"';}return'"'+e+(/^[a-z]+(-[a-z0-9]+)*$/i.test(t)?'"@'+t.toLowerCase():'"^^'+t)}};e.exports=n(n)},function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function a(e){return'function'==typeof e}function r(e){return'number'==typeof e}function o(e){return'object'==typeof e&&null!==e}function s(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!r(e)||0>e||isNaN(e))throw TypeError('n must be a positive number');return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,r,d,l,i;if(this._events||(this._events={}),'error'===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length))if(t=arguments[1],t instanceof Error)throw t;else{var p=new Error('Uncaught, unspecified "error" event. ('+t+')');throw p.context=t,p}if(n=this._events[e],s(n))return!1;if(a(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:d=Array.prototype.slice.call(arguments,1),n.apply(this,d);}else if(o(n))for(d=Array.prototype.slice.call(arguments,1),i=n.slice(),r=i.length,l=0;lr&&(this._events[e].warned=!0,console.error('(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.',this._events[e].length),'function'==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!a(t))throw TypeError('listener must be a function');var r=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,r,s,d;if(!a(t))throw TypeError('listener must be a function');if(!this._events||!this._events[e])return this;if(n=this._events[e],s=n.length,r=-1,n===t||a(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit('removeListener',e,t);else if(o(n)){for(d=s;0r)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit('removeListener',e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)'removeListener'!==t&&this.removeAllListeners(t);return this.removeAllListeners('removeListener'),this._events={},this}if(n=this._events[e],a(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?a(this._events[e])?[this._events[e]]:this._events[e].slice():[],t},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(a(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){t=e.exports=n(46),t.Stream=t,t.Readable=t,t.Writable=n(30),t.Duplex=n(8),t.Transform=n(52),t.PassThrough=n(72)},function(e,t,n){'use strict';(function(t,r,o){function i(e,t,n){this.chunk=e,this.encoding=t,this.callback=n,this.next=null}function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){R(t,e)}}function d(e){return A.from(e)}function l(e){return A.isBuffer(e)||e instanceof P}function p(){}function u(e,t){O=O||n(8),e=e||{};var r=t instanceof O;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var o=e.highWaterMark,i=e.writableHighWaterMark,d=this.objectMode?16:16384;this.highWaterMark=o||0===o?o:r&&(i||0===i)?i:d,this.highWaterMark=a(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var l=!1===e.decodeStrings;this.decodeStrings=!l,this.defaultEncoding=e.defaultEncoding||'utf8',this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){_(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function c(e){return O=O||n(8),F.call(c,this)||this instanceof O?void(this._writableState=new u(e,this),this.writable=!0,e&&('function'==typeof e.write&&(this._write=e.write),'function'==typeof e.writev&&(this._writev=e.writev),'function'==typeof e.destroy&&(this._destroy=e.destroy),'function'==typeof e.final&&(this._final=e.final)),U.call(this)):new c(e)}function h(e,t){var n=new Error('write after end');e.emit('error',n),C.nextTick(t,n)}function f(e,t,n,a){var r=!0,o=!1;return null===n?o=new TypeError('May not write null values to stream'):'string'!=typeof n&&void 0!==n&&!t.objectMode&&(o=new TypeError('Invalid non-string/buffer chunk')),o&&(e.emit('error',o),C.nextTick(a,o),r=!1),r}function g(e,t,n){return e.objectMode||!1===e.decodeStrings||'string'!=typeof t||(t=A.from(t,n)),t}function m(e,t,n,a,r,o){if(!n){var i=g(t,a,r);a!==i&&(n=!0,r='buffer',a=i)}var s=t.objectMode?1:a.length;t.length+=s;var d=t.length'},_encodeLiteral:function(e,t,n){return s.test(e)&&(e=e.replace(d,a)),n?'"'+e+'"@'+n:t?'"'+e+'"^^'+this._encodeIriOrBlankNode(t):'"'+e+'"'},_encodeSubject:function(e){if('"'===e[0])throw new Error('A literal as subject is not allowed: '+e);return'['===e[0]&&(this._subject=']'),this._encodeIriOrBlankNode(e)},_encodePredicate:function(e){if('"'===e[0])throw new Error('A literal as predicate is not allowed: '+e);return e===i?'a':this._encodeIriOrBlankNode(e)},_encodeObject:function(e){if('"'!==e[0])return this._encodeIriOrBlankNode(e);var t=r.exec(e);if(!t)throw new Error('Invalid literal: '+e);return this._encodeLiteral(t[1],t[2],t[3])},_blockedWrite:function(){throw new Error('Cannot write because the writer has been closed.')},addTriple:function(e,t,n,a,r){n===void 0?this._writeTriple(e.subject,e.predicate,e.object,e.graph||'',t):'string'==typeof a?this._writeTriple(e,t,n,a,r):this._writeTriple(e,t,n,'',a)},addTriples:function(e){for(var t=0;t.\n'))}if(a){var i='',s='';for(var d in n)i+=i?'|'+d:d,s+=(s?'|':'')+n[d];i=i.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,'\\$&'),this._prefixRegex=new RegExp('^(?:'+s+')[^/]*$|^('+i+')([a-zA-Z][\\-_a-zA-Z0-9]*)$')}this._write(a?'\n':'',t)},blank:function(e,t){var n=e,a,r;switch(void 0===e?n=[]:'string'==typeof e?n=[{predicate:e,object:t}]:!('length'in e)&&(n=[e]),r=n.length){case 0:return'[]';case 1:if(a=n[0],'['!==a.object[0])return'[ '+this._encodePredicate(a.predicate)+' '+this._encodeObject(a.object)+' ]';default:for(var o='[',s=0;s]+\?>/)){t.addStatus(a.req,'Has an XML declaration. We\'ll assume it\'s XHTML as the content-type was text/html.\n');var i=new C(this.response);return i.parse(t,n,a,r)}if(n.match(/.*/)){t.addStatus(a.req,'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n');var s=new C(this.response);return s.parse(t,n,a,r)}if(n.match(/[^(/)){t.addStatus(a.req,'Has default namespace for XHTML, so switching to XHTMLHandler.\n');var d=new C(this.response);return d.parse(t,n,a,r)}var l=/([\s\S]+?)<\/title>/im.exec(n);return l&&o.add(a.resource,S.dc('title'),o.literal(l[1]),a.resource),o.add(a.resource,S.rdf('type'),S.link('WebPage'),t.appNode),t.addStatus(a.req,'non-XML HTML document, not parsed for data.'),t.doneFetch(a,this.response)}}],[{key:'toString',value:function e(){return'HTMLHandler'}},{key:'register',value:function e(t){t.mediatypes['text/html']={q:.9}}}]),t}(j);O.pattern=/text\/html/;var E=function(e){function t(){return p(this,t),i(this,d(t).apply(this,arguments))}return l(t,e),o(t,[{key:'parse',value:function e(t,n,a,r){if(n.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)){t.addStatus(a.req,'Warning: '+a.resource+' has an XML declaration. We\'ll assume it\'s XML but its content-type wasn\'t XML.\n');var o=new L(this.response);return o.parse(t,n,a,r)}if(n.slice(0,500).match(/xmlns:/)){t.addStatus(a.req,'May have an XML namespace. We\'ll assume it\'s XML but its content-type wasn\'t XML.\n');var i=new L(this.response);return i.parse(t,n,a,r)}return t.addStatus(a.req,'Plain text document, no known RDF semantics.'),t.doneFetch(a,this.response)}}],[{key:'toString',value:function e(){return'TextHandler'}},{key:'register',value:function e(t){t.mediatypes['text/plain']={q:.5}}}]),t}(j);E.pattern=/text\/plain/;var D=function(e){function t(){return p(this,t),i(this,d(t).apply(this,arguments))}return l(t,e),o(t,[{key:'parse',value:function e(t,n,a,r){var o=t.store,i=f(o,o,a.original.uri,a.original.uri,null,null,'',null);try{i.loadBuf(n)}catch(e){var s='Error trying to parse '+a.resource+' as Notation3:\n'+e+':\n'+e.stack;return t.failFetch(a,s,'parse_error',r)}return t.addStatus(a.req,'N3 parsed: '+i.statementCount+' triples in '+i.lines+' lines.'),t.store.add(a.original,S.rdf('type'),S.link('RDFDocument'),t.appNode),t.doneFetch(a,this.response)}}],[{key:'toString',value:function e(){return'N3Handler'}},{key:'register',value:function e(t){t.mediatypes['text/n3']={q:'1.0'},t.mediatypes['text/turtle']={q:1}}}]),t}(j);D.pattern=/(application|text)\/(x-)?(rdf\+)?(n3|turtle)/;var U={RDFXMLHandler:R,XHTMLHandler:C,XMLHandler:L,HTMLHandler:O,TextHandler:E,N3Handler:D},A=function(){function e(t){var n=this,a=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(p(this,e),this.store=t||new c,this.timeout=a.timeout||3e4,this._fetch=a.fetch||T,!this._fetch)throw new Error('No _fetch function availble for Fetcher');this.appNode=this.store.bnode(),this.store.fetcher=this,this.requested={},this.timeouts={},this.redirectedTo={},this.fetchQueue={},this.fetchCallbacks={},this.nonexistent={},this.lookedUp={},this.handlers=[],this.mediatypes={"image/*":{q:.9},"*/*":{q:.1}},v.callbackify(this,['request','fail','refresh','retract','done']),Object.keys(U).map(function(e){return n.addHandler(U[e])})}return o(e,[{key:'load',value:function e(t){var n=this,a=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(t instanceof Array)return Promise.all(t.map(function(e){return n.load(e,Object.assign({},a))}));var r=t.uri||t;return r=r.split('#')[0],a=this.initFetchOptions(r,a),this.pendingFetchPromise(r,a.baseURI,a)}},{key:'pendingFetchPromise',value:function e(t,n,a){var r=this,o;return!a.force&&this.fetchQueue[n]?o=this.fetchQueue[n]:(o=Promise.race([this.setRequestTimeout(t,a),this.fetchUri(t,a)]),this.fetchQueue[n]=o,this.cleanupFetchRequest(n,a,this.timeout)),o.then(function(e){return t in r.timeouts&&(r.timeouts[t].forEach(clearTimeout),delete r.timeouts[t]),e})}},{key:'cleanupFetchRequest',value:function e(t,n,a){var r=this;this.timeouts[t]=(this.timeouts[t]||[]).concat(setTimeout(function(){r.isPending(t)||delete r.fetchQueue[t]},a))}},{key:'initFetchOptions',value:function t(n,a){var r=this.store,o=!a.method||'GET'===a.method.toUpperCase();o||(a.force=!0),a.resource=r.sym(n),a.baseURI=a.baseURI||n,a.original=r.sym(a.baseURI),a.req=r.bnode(),a.headers=a.headers||{},a.contentType&&(a.headers['content-type']=a.contentType),a.force&&(a.cache='no-cache');var i=this.acceptString();a.headers.accept=i;var s=e.offlineOverride(n);a.requestedURI=s,e.withCredentials(s,a)&&(a.credentials='include');var d=e.proxyIfNecessary(s);return s!==d&&(a.proxyUsed=!0),a.actualProxyURI=d,a}},{key:'fetchUri',value:function t(n,a){var r=this;if(!n)return Promise.reject(new Error('Cannot fetch an empty uri'));if(e.unsupportedProtocol(n))return this.failFetch(a,'fetcher: Unsupported protocol','unsupported_protocol');var o=this.getState(n);if(!a.force){if('fetched'===o)return Promise.resolve(this.doneFetch(a,{status:200,ok:!0,statusText:'Already loaded into quadstore.'}));if('failed'===o&&404===this.requested[n]){var i='Previously failed: '+this.requested[n],s={url:n,status:this.requested[n],statusText:i,responseText:i,headers:{},ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.failFetch(a,i,this.requested[n],s)}}else delete this.nonexistent[n];this.fireCallbacks('request',[n]),this.requested[n]=!0,a.noMeta||this.saveRequestMetadata(n,a);var d=a.actualProxyURI;return this._fetch(d,a).then(function(e){return r.handleResponse(e,n,a)},function(e){var t={url:d,status:999,statusText:(e.name||'network failure')+': '+(e.errno||e.code||e.type),responseText:e.message,headers:{},ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return console.log('Fetcher: <'+d+'> Non-HTTP fetch error: '+e),r.failFetch(a,'fetch failed: '+e,999,t)})}},{key:'nowOrWhenFetched',value:function e(t,n,a){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{};t=t.uri||t,'function'==typeof n?a=n:'undefined'==typeof n||(n instanceof g?r.referringTerm=n:r=n),this.load(t,r).then(function(e){if(a)if(!e){var n='@@ nowOrWhenFetched: no response object!';console.log(n),a(!1,n)}else if(e.ok)a(!0,'OK',e);else{console.log('@@@ fetcher.js Should not take this path !!!!!!!!!!!!');var r='HTTP error: Status '+e.status+' ('+e.statusText+')';e.responseText&&(r+=' '+e.responseText),console.log(r+' fetching '+t),a(!1,r,e)}},function(e){var n=e.message||e.statusText;n='Failed to load <'+t+'> '+n,console.log(n),e.response&&e.response.status&&(n+=' status: '+e.response.status),a(!1,n,e.response)})}},{key:'addStatus',value:function e(t,n){var a=new Date;n='['+a.getHours()+':'+a.getMinutes()+':'+a.getSeconds()+'.'+a.getMilliseconds()+'] '+n;var r=this.store,o=r.the(t,S.link('status'));o&&o.append?o.append(r.literal(n)):h.warn('web.js: No list to add to: '+o+','+n)}},{key:'failFetch',value:function e(t,n,a,r){this.addStatus(t.req,n),t.noMeta||this.store.add(t.original,S.link('error'),n);var o=(t.method||'GET').toUpperCase(),i='GET'===o||'HEAD'===o;i&&(t.resource.sameTerm(t.original)?console.log('@@ Recording '+o+' failure for '+t.original+': '+a):console.log('@@ Recording failure '+o+' original '+t.original+'( as '+t.resource+') : '+a),this.requested[_.docpart(t.original.uri)]=a,this.fireCallbacks('fail',[t.original.uri,n]));var s=new Error('Fetcher: '+n);return s.status=a,s.statusText=n,s.response=r,Promise.reject(s)}},{key:'linkData',value:function e(t,n,a,r,o){if(a){var i=this.store,s=i.sym(_.join(a,t.uri)),d;if('alternate'===n||'seeAlso'===n||'meta'===n||'describedby'===n){if(s.uri===t.uri)return;d=S.rdfs('seeAlso')}else d='type'===n?i.sym('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'):i.sym(_.join(encodeURIComponent(n),'http://www.iana.org/assignments/link-relations/'));o?i.add(s,d,t,r):i.add(t,d,s,r)}}},{key:'parseLinkHeader',value:function e(t,n,a){if(t)for(var r=/<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g,o=/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g,d=t.match(r),l=0;l<d.length;l++)for(var i=d[l].split('>'),u=i[0].substring(1),c=i[1],h=c.match(o),s=0;s<h.length;s++){var f=h[s],p=f.split('='),g=p[1].replace(/["']/g,'');this.linkData(n,g,u,a)}}},{key:'doneFetch',value:function e(t,n){return this.addStatus(t.req,'Done.'),this.requested[t.original.uri]='done',this.fireCallbacks('done',[t.original.uri]),n.req=t.req,n}},{key:'nowKnownAs',value:function e(t,n){this.lookedUp[t.uri]?!this.lookedUp[n.uri]&&this.lookUpThing(n,t):this.lookedUp[n.uri]&&!this.lookedUp[t.uri]&&this.lookUpThing(t,n)}},{key:'putBack',value:function e(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};t=t.uri||t;var a=new g(t).doc();return n.contentType=n.contentType||'text/turtle',n.data=w(a,this.store,a.uri,n.contentType),this.webOperation('PUT',t,n)}},{key:'webCopy',value:function e(t,n,a){var r=this;return this.webOperation('GET',t).then(function(e){return r.webOperation('PUT',n,{data:e.responseText,contentType:a})})}},{key:'delete',value:function e(t,n){var a=this;return this.webOperation('DELETE',t,n).then(function(e){return a.requested[t]=404,a.nonexistent[t]=!0,a.unload(a.store.sym(t)),e})}},{key:'createContainer',value:function e(t,n,a){var r={"content-type":'text/turtle',link:S.ldp('BasicContainer')+'; rel="type"'};n&&(r.slug=n);var o={headers:r};return a&&(o.body=a),this.webOperation('POST',t,o)}},{key:'webOperation',value:function t(n,a){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};a=a.uri||a,r.method=n,r.body=r.data||r.body,r.force=!0;var o=this;if(r.body&&!r.contentType)throw new Error('Web operation sending data must have a defined contentType.');return r.contentType&&(r.headers=r.headers||{},r.headers['content-type']=r.contentType),e.withCredentials(a,r)&&(r.credentials='include'),new Promise(function(e,t){o._fetch(a,r).then(function(r){if(r.ok)r.body?r.text().then(function(t){r.responseText=t,e(r)}):e(r);else{var o='Web error: '+r.status;r.statusText&&(o+=' ('+r.statusText+')'),o+=' on '+n+' of <'+a+'>',r.responseText&&(o+=': '+r.responseText);var i=new Error(o);i.response=r,t(i)}},function(e){var r='Fetch error for '+n+' of <'+a+'>:'+e;t(new Error(r))})})}},{key:'lookUpThing',value:function e(t,n){var a=this,r=this.store.uris(t);return r=r.map(function(e){return _.docpart(e)}),r.forEach(function(e){a.lookedUp[e]=!0}),this.load(r,{referringTerm:n})}},{key:'getHeader',value:function e(t,n){for(var a=this.store,o=a.each(void 0,S.link('requestedURI'),t.uri),i=0,r;i<o.length;i++)if(r=o[i],void 0!==r){var s=a.any(r,S.link('response'));if(void 0!==s){console.log('@@@ looking for '+S.httph(n.toLowerCase()));var d=a.each(s,S.httph(n.toLowerCase()));return d.length?d.map(function(e){return e.value}):[]}}}},{key:'saveRequestMetadata',value:function e(t,n){var a=n.req,r=this.store,o=n.referringTerm;this.addStatus(n.req,'Accept: '+n.headers.accept),o&&o.uri&&r.add(t,S.link('requestedBy'),o.uri,this.appNode),n.original&&n.original.uri!==t&&r.add(a,S.link('orginalURI'),r.literal(n.original.uri),this.appNode);var i=new Date,s='['+i.getHours()+':'+i.getMinutes()+':'+i.getSeconds()+'] ';r.add(a,S.rdfs('label'),r.literal(s+' Request for '+t),this.appNode),r.add(a,S.link('requestedURI'),r.literal(t),this.appNode),r.add(a,S.link('status'),r.collection(),this.appNode)}},{key:'saveResponseMetadata',value:function e(t,n){var a=this.store,r=a.bnode();return(a.add(n.req,S.link('response'),r,r),a.add(r,S.http('status'),a.literal(t.status),r),a.add(r,S.http('statusText'),a.literal(t.statusText),r),!n.resource.uri.startsWith('http'))?r:(t.headers.forEach(function(e,t){a.add(r,S.httph(t),e,r),'content-type'===t&&a.add(n.resource,S.rdf('type'),v.mediaTypeClass(e),r)}),r)}},{key:'objectRefresh',value:function e(t){var n=this.store.uris(t);if('undefined'!=typeof n)for(var a=0;a<n.length;a++)this.refresh(this.store.sym(_.docpart(n[a])))}},{key:'refresh',value:function e(t,n){this.fireCallbacks('refresh',arguments),this.nowOrWhenFetched(t,{force:!0,clearPreviousData:!0},n)}},{key:'refreshIfExpired',value:function e(t,n){var a=this.getHeader(t,'Expires');!a||new Date(a).getTime()<=new Date().getTime()?this.refresh(t,n):n(!0,'Not expired',{})}},{key:'retract',value:function e(t){this.store.removeMany(void 0,void 0,void 0,t),t.uri&&delete this.requested[_.docpart(t.uri)],this.fireCallbacks('retract',arguments)}},{key:'getState',value:function e(t){return'undefined'==typeof this.requested[t]?'unrequested':!0===this.requested[t]?'requested':'done'===this.requested[t]?'fetched':'redirected'===this.requested[t]?this.getState(this.redirectedTo[t]):'failed'}},{key:'isPending',value:function e(t){return!0===this.requested[t]}},{key:'unload',value:function e(t){this.store.removeDocument(t),delete this.requested[t.uri]}},{key:'addHandler',value:function e(t){this.handlers.push(t),t.register(this)}},{key:'retryNoCredentials',value:function e(t,n){console.log('web: Retrying with no credentials for '+n.resource),n.retriedWithNoCredentials=!0,delete this.requested[t];var a=Object.assign({},n,{withCredentials:!1});return this.addStatus(n.req,'Abort: Will retry with credentials SUPPRESSED to see if that helps'),this.load(t,a)}},{key:'isCrossSite',value:function e(t){if('undefined'==typeof document||!document.location)return!1;var n=_.hostpart,a=''+document.location;return n(a)&&n(t)&&n(a)!==n(t)}},{key:'handleError',value:function t(n,a,r){if(this.isCrossSite(a)){if(r.withCredentials&&!r.retriedWithNoCredentials)return this.retryNoCredentials(a,r);var o=e.crossSiteProxy(a);if(o&&!r.proxyUsed)return console.log('web: Direct failed so trying proxy '+o),this.redirectToProxy(o,r)}var i;return n.message?i='Fetch error: '+n.message:(i=n.statusText,n.responseText&&(i+=' '.concat(n.responseText))),this.failFetch(r,i,n.status||998,n)}},{key:'addType',value:function e(t,n,a,r){var o=n;if(r){var i=a.any(o,S.link('requestedURI'));i&&i!==r&&a.add(a.sym(r),S.rdf('type'),t,this.appNode)}for(;;){var s=a.any(o,S.link('requestedURI'));if(s&&s.value&&a.add(a.sym(s.value),S.rdf('type'),t,this.appNode),o=a.any(void 0,a.sym('http://www.w3.org/2007/ont/link#redirectedRequest'),o),!o)break;var d=a.any(o,a.sym('http://www.w3.org/2007/ont/link#response'));if(!d)break;var l=a.any(d,a.sym('http://www.w3.org/2007/ont/http#status'));if(!l)break;if('301'!==l&&'302'!==l)break}}},{key:'handleResponse',value:function e(t,n,a){var r=this,o=this.store,i=t.headers,s=a.req,d=this.saveResponseMetadata(t,a),l=this.normalizedContentType(a,i)||'',p=i.get('content-location');if(0===t.status)return console.log('Masked error - status 0 for '+n),this.handleError(t,n,a);if(400<=t.status)return 404===t.status&&(this.nonexistent[a.original.uri]=!0,this.nonexistent[n]=!0),this.saveErrorResponse(t,d).then(function(){var e=a.resource+' '+t.statusText;return r.failFetch(a,e,t.status,t)});var u=null,c=null;if(p&&(c=_.join(p,n),c!==n&&(u=c)),200===t.status){this.addType(S.link('Document'),s,o,n),u&&this.addType(S.link('Document'),s,o,u),a.clearPreviousData&&o.removeDocument(a.resource);var h=l.includes('image/')||l.includes('application/pdf');l&&h&&(this.addType(o.sym('http://purl.org/dc/terms/Image'),s,o,n),u&&this.addType(o.sym('http://purl.org/dc/terms/Image'),s,o,u))}if(p){if(!a.force&&u&&'done'===this.requested[c])return this.doneFetch(a,t);this.requested[c]=!0}this.parseLinkHeader(i.get('link'),a.original,s);var f=this.handlerForContentType(l,t);return f?t.text().then(function(e){return t.responseText=e,f.parse(r,e,a,t)}):(this.addStatus(s,'Fetch over. No data handled.'),this.doneFetch(a,t))}},{key:'saveErrorResponse',value:function e(t,n){var a=this.store;return t.text().then(function(e){10<e.length&&a.add(n,S.http('content'),a.literal(e),n)})}},{key:'handlerForContentType',value:function e(t,n){if(!t)return null;var a=this.handlers.find(function(e){return t.match(e.pattern)});return a?new a(n):null}},{key:'guessContentType',value:function e(t){return I[t.split('.').pop()]}},{key:'normalizedContentType',value:function e(t,n){if(t.forceContentType)return t.forceContentType;var a=n.get('content-type');if(!a||a.includes('application/octet-stream')){var r=this.guessContentType(t.resource.uri);if(r)return r}var o=_.protocol(t.resource.uri);return!a&&['file','chrome'].includes(o)?'text/xml':a}},{key:'redirectToProxy',value:function e(t,n){var a=this;this.addStatus(n.req,'BLOCKED -> Cross-site Proxy to <'+t+'>'),n.proxyUsed=!0;var r=this.store,o=n.req;n.noMeta||(r.add(o,S.link('redirectedTo'),r.sym(t),o),this.addStatus(o,'redirected to new request')),this.requested[n.resource.uri]='redirected',this.redirectedTo[n.resource.uri]=t;var i=Object.assign({},n);return i.baseURI=n.resource.uri,this.fetchUri(t,i).then(function(e){return i.noMeta||r.add(o,S.link('redirectedRequest'),i.req,a.appNode),e})}},{key:'setRequestTimeout',value:function e(t,n){var a=this;return new Promise(function(e){a.timeouts[t]=(a.timeouts[t]||[]).concat(setTimeout(function(){!a.isPending(t)||n.retriedWithNoCredentials||n.proxyUsed||e(a.failFetch(n,'Request to '.concat(t,' timed out'),'timeout'))},a.timeout))})}},{key:'addFetchCallback',value:function e(t,n){this.fetchCallbacks[t]?this.fetchCallbacks[t].push(n):this.fetchCallbacks[t]=[n]}},{key:'acceptString',value:function e(){var t='';for(var n in this.mediatypes)for(var a in''!=t&&(t+=', '),t+=n,this.mediatypes[n])t+=';'+a+'='+this.mediatypes[n][a];return t}}],[{key:'crossSiteProxy',value:function t(n){return e.crossSiteProxyTemplate?e.crossSiteProxyTemplate.replace('{uri}',encodeURIComponent(n)):void 0}},{key:'offlineOverride',value:function e(t){var n=t,a;return'undefined'!=typeof window&&window.panes&&(a=window.panes.UI)&&a.preferences&&a.preferences.get('offlineModeUsingLocalhost')&&'http://'===n.slice(0,7)&&'localhost/'!==n.slice(7,17)&&(n='http://localhost/'+n.slice(7),h.warn('Localhost kludge for offline use: actually getting <'+n+'>')),n}},{key:'proxyIfNecessary',value:function t(n){var a;if('undefined'!=typeof window&&window.panes&&(a=window.panes.UI)&&a.isExtension)return n;if('undefined'!=typeof $SolidTestEnvironment&&$SolidTestEnvironment.localSiteMap){var r=n.split('/').slice(2),o=function e(t,n){var a=n[t.shift()];return a?'string'==typeof a?a+t.join('/'):t?e(t,a):null:null},i=o(r,$SolidTestEnvironment.localSiteMap);if(i)return i}return e.crossSiteProxyTemplate&&'undefined'!=typeof document&&document.location&&'https:'===(''+document.location).slice(0,6)&&'http:'===n.slice(0,5)?e.crossSiteProxyTemplate.replace('{uri}',encodeURIComponent(n)):n}},{key:'unsupportedProtocol',value:function e(t){var n=_.protocol(t);return'tel'===n||'mailto'===n||'urn'===n}},{key:'withCredentials',value:function e(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},e=t.startsWith('https:');return void 0!==n.withCredentials&&(e=n.withCredentials),e}}]),e}();e.exports=A,e.exports.HANDLERS=U,e.exports.CONTENT_TYPE_BY_EXT=I},function(e,t,n){function a(e,t,n,a,i,s){function d(e,t){return i?void i(e,t):t}n=n||e.uri,s=s||{},a=a||'text/turtle';var l=null;try{var p=o(t);s.flags&&p.setFlags(s.flags);var u=t.statementsMatching(void 0,void 0,void 0,e),c;switch(p.suggestNamespaces(t.namespaces),p.setBase(n),a){case'application/rdf+xml':return l=p.statementsToXML(u),d(null,l);case'text/n3':case'application/n3':return l=p.statementsToN3(u),d(null,l);case'text/turtle':case'application/x-turtle':return p.setFlags('si'),l=p.statementsToN3(u),d(null,l);case'application/n-triples':return p.setFlags('deinprstux'),l=p.statementsToNTriples(u),d(null,l);case'application/ld+json':p.setFlags('deinprstux'),c=p.statementsToNTriples(u),r.convertToJson(c,i);break;case'application/n-quads':case'application/nquads':return p.setFlags('deinprstux q'),l=p.statementsToNTriples(u),d(null,l);break;default:throw new Error('Serialize: Content-type '+a+' not supported for data write.');}}catch(e){if(i)return i(e);throw e}}e.exports=a;var r=n(38),o=n(34)},function(e,t,n){var a=n(0),r=n(6),o=n(2),i=n(4),s=n(37),d=function(){function e(e){return encodeURI(e)}function t(e){for(var t='',n=0,a;n<e.length;n++)a=e.charCodeAt(n),t+=65535<a?'\\U'+('00000000'+a.toString(16)).slice(-8):126<a?'\\u'+('0000'+a.toString(16)).slice(-4):e[n];return t}var n=function e(t){this.flags='',this.base=null,this.prefixes=[],this.namespaces=[],this.suggestPrefix('rdf','http://www.w3.org/1999/02/22-rdf-syntax-ns#'),this.suggestPrefix('xml','reserved:reservedForFutureUse'),this.namespacesUsed=[],this.keywords=['a'],this.prefixchars='abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',this.incoming=null,this.formulas=[],this.store=t};n.prototype.setBase=function(e){return this.base=e,this},n.prototype.setFlags=function(e){return this.flags=e||'',this},n.prototype.toStr=function(e){var t=e.toNT();return'Graph'===e.termType&&(this.formulas[t]=e),t},n.prototype.fromStr=function(e){if('{'===e[0]){var t=this.formulas[e];return t||console.log('No formula object for '+e),t}return this.store.fromNT(e)},n.prototype.suggestPrefix=function(e,t){'default'===e.slice(0,7)||'ns'===e.slice(0,2)||!e||!t||e in this.namespaces||t in this.prefixes||(this.prefixes[t]=e,this.namespaces[e]=t)},n.prototype.suggestNamespaces=function(e){for(var t in e)return this.suggestPrefix(t,e[t]),this},n.prototype.checkIntegrity=function(){var e,t;for(e in this.namespaces)if(this.prefixes[this.namespaces[e]]!==e)throw new Error('Serializer integity error 1: '+e+', '+this.namespaces[e]+', '+this.prefixes[this.namespaces[e]]+'!');for(t in this.prefixes)if(this.namespaces[this.prefixes[t]]!==t)throw new Error('Serializer integity error 2: '+t+', '+this.prefixs[t]+', '+this.namespaces[this.prefixes[t]]+'!')},n.prototype.makeUpPrefix=function(e){function t(t){return!!n.prototype.validPrefix.test(t)&&'ns'!==t&&!(t in this.namespaces)&&(this.prefixes[e]=t,this.namespaces[t]=e,t)}var a=e,r=t.bind(this);0<='#/'.indexOf(a[a.length-1])&&(a=a.slice(0,-1));var o=a.lastIndexOf('/');0<=o&&(a=a.slice(o+1));for(var s=0;s<a.length&&this.prefixchars.indexOf(a[s]);)s++;if(a=a.slice(0,s),6>a.length&&r(a))return a;if(r(a.slice(0,3)))return a.slice(0,3);if(r(a.slice(0,2)))return a.slice(0,2);if(r(a.slice(0,4)))return a.slice(0,4);if(r(a.slice(0,1)))return a.slice(0,1);if(r(a.slice(0,5)))return a.slice(0,5);n.prototype.validPrefix.test(a)||(a='n');for(var i=0;;i++)if(r(a.slice(0,3)+i))return a.slice(0,3)+i},n.prototype.rootSubjects=function(e){for(var t={},n={},a={},r=0;r<e.length;r++){var o=e[r],i=function e(n){t.hasOwnProperty(n)||(t[n]=[]),t[n].push(o.subject)},s=[o.subject,o.predicate,o.object];s.map(function(e){'BlankNode'===e.termType?a[e.toNT()]=!0:'Collection'===e.termType&&e.elements.forEach(function(e){i(e)})}),i(e[r].object);var d=n[this.toStr(o.subject)];d||(d=[]),d.push(o),n[this.toStr(o.subject)]=d}var l=[];for(var p in n)if(n.hasOwnProperty(p)){var u=this.fromStr(p);if('BlankNode'!==u.termType||!t[u]||1!==t[u].length){l.push(u);continue}}this.incoming=t;for(var c={},h=0;h<l.length;h++)c[l[h].toNT()]=!0;return{roots:l,subjects:n,rootsHash:c,incoming:t}},n.prototype.toN3=function(e){return this.statementsToN3(e.statements)},n.prototype._notQNameChars='\t\r\n !"#$%&\'()*.,+/;<=>?@[\\]^`{|}~',n.prototype._notNameChars=n.prototype._notQNameChars+':',n.prototype.explicitURI=function(n){return n=0>this.flags.indexOf('r')&&this.base?o.refTo(this.base,n):0<=this.flags.indexOf('u')?t(n):e(n),'<'+n+'>'},n.prototype.statementsToNTriples=function(e){var t=e.slice();t.sort();for(var n='',a='http://www.w3.org/1999/02/22-rdf-syntax-ns#',o=this,d=this.store,l=function e(t){if('Collection'!==t.termType)return o.atomicTermToN3(t);for(var s=t.elements,l=d.sym(a+'nill'),p=s.length-1,i;0<=p;p--)i=new r,n+=e(i)+' '+e(d.sym(a+'first'))+' '+e(s[p])+'.\n',n+=e(i)+' '+e(d.sym(a+'rest'))+' '+e(l)+'.\n',l=i;return o.atomicTermToN3(l)},p=0;p<t.length;p++){var i=t[p],u='';u+=l(i.subject)+' ',u+=l(i.predicate)+' ',u+=l(i.object)+' ',0<=this.flags.indexOf('q')&&(u+=l(i.why)+' '),u+='.\n',n+=u}return n},n.prototype.statementsToN3=function(e){function t(e){for(var t=this.rootSubjects(e),n=t.roots,r=[],o=0,i;o<n.length;o++)i=n[o],r.push(a(i,t));return r}function a(e,t){return'BlankNode'!==e.termType||t.incoming[e]?[v(e,t)].concat([x(e,t)]).concat(['.']):_(e,t,!0).concat(['.'])}function r(e,t){var n=[],a=null,r=t.subjects[this.toStr(e)]||[];if('undefined'==typeof r)throw new Error('Cant find statements for '+e);for(var o=[],s=0,i;s<r.length;s++)i=r[s],i.predicate.uri===a?o.push(','):(a&&(n=n.concat([o]).concat([';']),o=[]),n.push(f[i.predicate.uri]?f[i.predicate.uri]:v(i.predicate,t))),a=i.predicate.uri,o.push(_(i.object,t));return n=n.concat([o]),n}function o(e,t,n){return'BlankNode'===e.termType&&(n||void 0===t.rootsHash[e.toNT()])?t.subjects[this.toStr(e)]?['[',x(e,t),']']:'[]':v(e,t)}function s(e,t){var n,a;switch(e.termType){case'Graph':return a=['{'],a=a.concat(b(e.statements)),a.concat(['}']);case'Collection':for(a=['('],n=0;n<e.elements.length;n++)a.push([_(e.elements[n],t)]);return a.push(')'),a;default:return this.atomicTermToN3(e);}}function d(){var e='';for(var t in this.defaultNamespace&&(e+='@prefix : '+this.explicitURI(this.defaultNamespace)+'.\n'),this.prefixes)this.prefixes.hasOwnProperty(t)&&this.namespacesUsed[t]&&(e+='@prefix '+this.prefixes[t]+': '+this.explicitURI(t)+'.\n');return e+'\n'}var l=4,p=80,u=this.store,c={"http://www.w3.org/1999/02/22-rdf-syntax-ns#type":'aaa:00'},h=function e(t,n){return i.heavyCompareSPO(t,n,u,c)};e.sort(h),this.base&&!this.defaultNamespace&&(this.defaultNamespace=this.base+'#');var f={};0>this.flags.indexOf('s')&&(f['http://www.w3.org/2002/07/owl#sameAs']='='),0>this.flags.indexOf('t')&&(f['http://www.w3.org/1999/02/22-rdf-syntax-ns#type']='a'),0>this.flags.indexOf('i')&&(f['http://www.w3.org/2000/10/swap/log#implies']='=>');var g=function e(t){for(var n='',a=0;a<t;a++)n+=' ';return n},m=function e(t){for(var n='',a=0;a<t.length;a++){var r=t[a],o='string'==typeof r?r:e(r);if(0!==a){var i=n.slice(-1)||' ';','!==o&&';'!==o&&('.'!==o||'0123456789.'.includes(i))&&(n+=' ')}n+=o}return n},y=function e(t,n){var a='',r=1e5;n===void 0&&(n=-1);for(var o=0,i;o<t.length;o++){if(i=t[o],'string'!=typeof i){var s=e(i,n+1);if(s.length<10*(p-l*n)&&0>s.indexOf('"""')){var d=m(i);d.length<p-l*n&&(i=d,s='')}s&&(r=1e4),a+=s}if('string'==typeof i){if(1===i.length&&'\n'===a.slice(-1)&&0<=',.;'.indexOf(i)){a=a.slice(0,-1)+i+'\n',r+=1;continue}if(r<l*n+4||r+i.length+1<p&&0>';.'.indexOf(a[a.length-2]))a=a.slice(0,-1)+' '+i+'\n',r+=i.length+1;else{var u=g(l*n)+i;a+=u+'\n',r=u.length,0>n&&(a+='\n',r=1e5)}}}return a},b=t.bind(this),x=r.bind(this),_=o.bind(this);n.prototype.termToN3=v;var v=s.bind(this),w=d.bind(this),k=b(e);return w()+y(k)},n.prototype.atomicTermToN3=function e(t,n){switch(t.termType){case'BlankNode':case'Variable':return t.toNT();case'Literal':var a=t.value;if('string'!=typeof a)throw new TypeError('Value of RDF literal node must be a string');if(t.datatype&&0>this.flags.indexOf('x'))switch(t.datatype.uri){case'http://www.w3.org/2001/XMLSchema#integer':return a;case'http://www.w3.org/2001/XMLSchema#decimal':return 0>a.indexOf('.')&&(a+='.0'),a;case'http://www.w3.org/2001/XMLSchema#double':return 0>a.indexOf('.')&&(a+='.0'),0>a.indexOf('e')&&(a+='e0'),a;case'http://www.w3.org/2001/XMLSchema#boolean':return'1'===t.value?'true':'false';}var r=this.stringToN3(t.value);return t.language?r+='@'+t.language:!t.datatype.equals(s.string)&&(r+='^^'+this.atomicTermToN3(t.datatype,n)),r;case'NamedNode':return this.symbolToN3(t);default:throw new Error('Internal: atomicTermToN3 cannot handle '+t+' of termType: '+t.termType);}},n.prototype.validPrefix=new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/),n.prototype.forbidden1=new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm),n.prototype.forbidden3=new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm),n.prototype.stringToN3=function e(t,a){a||(a='e');var r='',o,i,s,d,l;for(20<t.length&&'"'!==t.slice(-1)&&0>a.indexOf('n')&&(0<t.indexOf('\n')||0<t.indexOf('"'))?(d='"""',l=n.prototype.forbidden3):(d='"',l=n.prototype.forbidden1),o=0;o<t.length;){l.lastIndex=0;var p=l.exec(t.slice(o));if(null==p)break;i=o+l.lastIndex-1,r+=t.slice(o,i);var u=t[i];'"'===u&&'"""'===d&&'"""'!==t.slice(i,i+3)?r+=u:(s='\b\f\r\t\x0B\n\\"'.indexOf(u),r+=0<=s?'\\'+'bfrtvn\\"'[s]:0<=a.indexOf('e')?'\\u'+('000'+u.charCodeAt(0).toString(16).toLowerCase()).slice(-4):u),o=i+1}return d+r+t.slice(o)+d},n.prototype.symbolToN3=function e(t){var a=t.uri,r=a.indexOf('#');if(0>r&&0>this.flags.indexOf('/')&&(r=a.lastIndexOf('/')),0<=r&&0>this.flags.indexOf('p')&&(0===a.indexOf('http')||0===a.indexOf('ws')||0===a.indexOf('file'))){for(var o=!0,i=r+1;i<a.length;i++)if(0<=n.prototype._notNameChars.indexOf(a[i])){o=!1;break}if(o){var s=a.slice(r+1),d=a.slice(0,r+1);if(this.defaultNamespace&&this.defaultNamespace===d&&0>this.flags.indexOf('d'))return 0<=this.flags.indexOf('k')&&0>this.keyords.indexOf(s)?s:':'+s;var l=this.prefixes[d];if(l||(l=this.makeUpPrefix(d)),l)return this.namespacesUsed[d]=!0,l+':'+s}}return this.explicitURI(a)},n.prototype.writeStore=function(e){var t=this.store,n=t.fetcher,a=n&&n.appNode,r=this.store.index[3];for(var o in r){var i=t.fromNT(o);a&&i.sameTerm(a)||e('\n'+this.atomicTermToN3(i)+' '+this.atomicTermToN3(t.sym('http://www.w3.org/2000/10/swap/log#semantics'))+' { '+this.statementsToN3(t.statementsMatching(void 0,void 0,void 0,i))+' }.\n')}t.statementsMatching(void 0,t.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(function(n){e('\n<'+n.object.value+'> log:metadata {\n');var a=t.statementsMatching(void 0,void 0,void 0,n.subject);e(this.statementsToN3(this.statementsToN3(a))),e('}.\n')});var s=[];a&&s.push(a);var d=[];s.map(function(e){d=d.concat(t.statementsMatching(void 0,void 0,void 0,e))}),e(this.statementsToN3(d))},n.prototype.statementsToXML=function(e){function t(e){this.suggestPrefix('rdf','http://www.w3.org/1999/02/22-rdf-syntax-ns#');for(var t=this.rootSubjects(e),n=t.roots,a=[],r=0,o;r<n.length;r++)o=n[r],a.push(v(o,t));return a}function r(e){return'undefined'==typeof e?'@@@undefined@@@@':e.replace(/[&<"]/g,function(e){switch(e[0]){case'&':return'&';case'<':return'<';case'"':return'"';}})}function o(e){return r(this.base?i.uri.refTo(this.base,e.uri):e.uri)}function d(e,n){var o=[],d=n.subjects[this.toStr(e)],p,u,t,c;if('undefined'==typeof d)return w(e,n);d.sort(function(e,t){var n=e.predicate.uri,a=t.predicate.uri;if(n.substring(0,g.length)===g||a.substring(0,g.length)===g)return n.localeCompare(a);var r=n.substring(g.length),o=a.substring(g.length),i=parseInt(r,10),s=parseInt(o,10);return isNaN(i)||isNaN(s)||i!==r||s!==o?n.localeCompare(a):i-s});for(var h=0;h<d.length;h++){if(t=d[h],'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'===t.predicate.uri&&!p&&'symbol'===t.object.termType){p=t.object;continue}if(c=t.predicate,c.uri.substr(0,g.length)===g){var i=c.uri.substr(g.length),f=parseInt(i,10);i===f.toString()&&(c=new a('http://www.w3.org/1999/02/22-rdf-syntax-ns#li'))}switch(u=k(c),t.object.termType){case'BlankNode':o=1===n.incoming[t.object].length?o.concat(['<'+u+' rdf:parseType="Resource">',v(t.object,n),'</'+u+'>']):o.concat(['<'+u+' rdf:nodeID="'+t.object.toNT().slice(2)+'"/>']);break;case'NamedNode':o=o.concat(['<'+u+' rdf:resource="'+_(t.object)+'"/>']);break;case'Literal':o=o.concat(['<'+u+(t.object.datatype.equals(s.string)?'':' rdf:datatype="'+r(t.object.datatype.uri)+'"')+(t.object.language?' xml:lang="'+t.object.language+'"':'')+'>'+r(t.object.value)+'</'+u+'>']);break;case'Collection':o=o.concat(['<'+u+' rdf:parseType="Collection">',l(t.object,n),'</'+u+'>']);break;default:throw new Error('Can\'t serialize object of type '+t.object.termType+' into XML');}}var m=p?k(p):'rdf:Description',y='';return'BlankNode'===e.termType?(!n.incoming[e]||1!==n.incoming[e].length)&&(y=' rdf:nodeID="'+e.toNT().slice(2)+'"'):y=' rdf:about="'+_(e)+'"',['<'+m+y+'>'].concat([o]).concat(['</'+m+'>'])}function l(e,t){for(var n=[],a=0;a<e.elements.length;a++)n.push(v(e.elements[a],t));return n}function p(e,t){var n=[],a=t.subjects[this.toStr(e)];if(!a)return n;a.sort();for(var o=0,i;o<a.length;o++)switch(i=a[o],i.object.termType){case'BlankNode':n=t.rootsHash[i.object.toNT()]?n.concat(['<'+k(i.predicate)+' rdf:nodeID="'+i.object.toNT().slice(2)+'">','</'+k(i.predicate)+'>']):n.concat(['<'+k(i.predicate)+' rdf:parseType="Resource">',w(i.object,t),'</'+k(i.predicate)+'>']);break;case'NamedNode':n=n.concat(['<'+k(i.predicate)+' rdf:resource="'+_(i.object)+'"/>']);break;case'Literal':n=n.concat(['<'+k(i.predicate)+(i.object.datatype.equals(s.string)?'':' rdf:datatype="'+r(i.object.datatype.value)+'"')+(i.object.language?' xml:lang="'+i.object.language+'"':'')+'>'+r(i.object.value)+'</'+k(i.predicate)+'>']);break;case'Collection':n=n.concat(['<'+k(i.predicate)+' rdf:parseType="Collection">',l(i.object,t),'</'+k(i.predicate)+'>']);break;default:throw new Error('Can\'t serialize object of type '+i.object.termType+' into XML');}return n}function u(e){var t=e.uri,a=t.indexOf('#');if(0>a&&0>this.flags.indexOf('/')&&(a=t.lastIndexOf('/')),0>a)throw new Error('Cannot make qname out of <'+t+'>');for(var r=a+1;r<t.length;r++)if(0<=n.prototype._notNameChars.indexOf(t[r]))throw new Error('Invalid character "'+t[r]+'" cannot be in XML qname for URI: '+t);var o=t.slice(a+1),i=t.slice(0,a+1);if(this.defaultNamespace&&this.defaultNamespace===i&&0>this.flags.indexOf('d'))return o;var s=this.prefixes[i];return s||(s=this.makeUpPrefix(i)),f[i]=!0,s+':'+o}var c=4,h=80,f=[];f['http://www.w3.org/1999/02/22-rdf-syntax-ns#']=!0;var g='http://www.w3.org/1999/02/22-rdf-syntax-ns#_',m=function e(t){for(var n='',a=0;a<t;a++)n+=' ';return n},y=function e(t){for(var n='',a=0;a<t.length;a++){var r=t[a],o='string'==typeof r?r:e(r);n+=o}return n},b=function e(t,n){var a='',r=1e5,o;n||(n=0);for(var s=0,i;s<t.length;s++){if(i=t[s],'string'!=typeof i){var d=e(i,n+1);d.length<10*(h-c*n)&&0>d.indexOf('"""')&&(o=y(i),o.length<h-c*n&&(i=' '+o,d='')),d&&(r=1e4),a+=d}'string'==typeof i&&(r<c*n+4?(a=a.slice(0,-1)+' '+i+'\n',r+=i.length+1):(o=m(c*n)+i,a+=o+'\n',r=o.length))}return a},x=t.bind(this),_=o.bind(this),v=d.bind(this),w=p.bind(this),k=u.bind(this),T=x(e),N='<rdf:RDF';for(var I in this.defaultNamespace&&(N+=' xmlns="'+r(this.defaultNamespace)+'"'),f)if(f.hasOwnProperty(I)){var S=this.base&&this.flags.includes('z')?i.uri.refTo(this.base,I):I;N+='\n xmlns:'+this.prefixes[I]+'="'+r(S)+'"'}N+='>';var j=[N,T,'</rdf:RDF>'];return b(j,-1)};var d=function e(t){return new n(t)};return d}();e.exports=d},function(e,t,n){function a(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function r(e,t){for(var n=0,a;n<t.length;n++)a=t[n],a.enumerable=a.enumerable||!1,a.configurable=!0,'value'in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}function o(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}var i=n(6),s=n(11),d=n(20),l=n(0),p=n(2),u=n(4);if('undefined'==typeof c)var c={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 h=function(){function e(t,n){a(this,e),this.options=n||{},this.kb=t,this.target=n.target||{graph:{subjects:{},prefixes:{},terms:{}}},this.blankNodes=[],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=!1,this.absURIRE=/[\w\_\-]+:\S+/,this.finishedHandlers=[],this.init()}return o(e,[{key:'addTriple',value:function e(t,n,a,r){var o,i,s,l;o='undefined'==typeof n?d.namedNode(this.options.base):this.toRDFNodeObject(n),s=this.toRDFNodeObject(a),i=this.toRDFNodeObject(r),l=d.namedNode(this.options.base),this.kb.add(o,s,i,l)}},{key:'ancestorPath',value:function e(t){for(var n='';t&&t.nodeType!==c.DOCUMENT_NODE;)n='/'+t.localName+n,t=t.parentNode;return n}},{key:'copyMappings',value:function e(t){var n={};for(var a in t)n[a]=t[a];return n}},{key:'copyProperties',value:function e(){}},{key:'deriveDateTimeType',value:function t(n){for(var a=0,r;a<e.dateTimeTypes.length;a++)if(r=e.dateTimeTypes[a].pattern.exec(n),r&&r[0].length===n.length)return e.dateTimeTypes[a].type;return null}},{key:'init',value:function e(){}},{key:'newBlankNode',value:function e(){return this.blankCounter++,'_:'+this.blankCounter}},{key:'newSubjectOrigin',value:function e(t,n){}},{key:'parseCURIE',value:function t(n,a,r){var o=n.indexOf(':'),i;if(0<=o){var s=n.substring(0,o);if(''===s)return i=a[''],i?i+n.substring(o+1):null;if('_'===s)return'_:'+n.substring(o+1);if(e.NCNAME.test(s)&&(i=a[s],i))return i+n.substring(o+1)}return null}},{key:'parseCURIEOrURI',value:function e(t,n,a){var r=this.parseCURIE(t,n,a);return r?r:this.resolveAndNormalize(a,t)}},{key:'parsePredicate',value:function e(t,n,a,r,o,i){if(''===t)return null;var s=this.parseTermOrCURIEOrAbsURI(t,n,i?null:a,r,o);return s&&0===s.indexOf('_:')?null:s}},{key:'parsePrefixMappings',value:function e(t,n){for(var a=this.tokenize(t),r=null,o=0;o<a.length;o++)':'===a[o][a[o].length-1]?r=a[o].substring(0,a[o].length-1):r&&(n[r]=this.options.base?p.join(a[o],this.options.base):a[o],r=null)}},{key:'parseSafeCURIEOrCURIEOrURI',value:function e(t,n,a){return t=this.trim(t),'['===t.charAt(0)&&']'===t.charAt(t.length-1)?(t=t.substring(1,t.length-1),t=t.trim(t),0===t.length?null:'_:'===t?this.theOne:this.parseCURIE(t,n,a)):this.parseCURIEOrURI(t,n,a)}},{key:'parseTermOrCURIEOrAbsURI',value:function e(t,n,a,r,o){t=this.trim(t);var i=this.parseCURIE(t,r,o);if(i)return i;if(a){if(n&&!this.absURIRE.exec(t))return n+t;var s=a[t];if(s)return s;var d=t.toLowerCase();if(s=a[d],s)return s}return this.absURIRE.exec(t)?this.resolveAndNormalize(o,t):null}},{key:'parseTermOrCURIEOrURI',value:function e(t,n,a,r,o){t=this.trim(t);var i=this.parseCURIE(t,r,o);if(i)return i;var s=a[t];if(s)return s;var d=t.toLowerCase();return(s=a[d],s)?s:n&&!this.absURIRE.exec(t)?n+t:this.resolveAndNormalize(o,t)}},{key:'parseURI',value:function e(t){return t}},{key:'process',value:function t(n,a){var r;n.nodeType===c.DOCUMENT_NODE?(r=n.baseURI,n=n.documentElement,n.baseURI=r,this.setContext(n)):n.parentNode.nodeType===c.DOCUMENT_NODE&&this.setContext(n);var o=[],s=function e(t){if(!t&&a&&a.baseURI)return a.baseURI;var n=t.indexOf('#');return 0<=n&&(t=t.substring(0,n)),a&&a.baseURIMap&&(t=a.baseURIMap(t)),t};for(o.push({current:n,context:this.push(null,s(n.baseURI))});0<o.length;){var d=o.shift();if(d.parent){if(d.context.parent&&d.context.parent.listMapping===d.listMapping)continue;for(var l in d.listMapping){var u=d.listMapping[l];if(0===u.length){this.addTriple(d.parent,d.subject,l,{type:e.objectURI,value:'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'});continue}for(var h=[],f=0;f<u.length;f++)h.push(this.newBlankNode());for(var g=0;g<h.length;g++)this.addTriple(d.parent,h[g],'http://www.w3.org/1999/02/22-rdf-syntax-ns#first',u[g]),this.addTriple(d.parent,h[g],'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest',{type:e.objectURI,value:g+1<h.length?h[g+1]:'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'});this.addTriple(d.parent,d.subject,l,{type:e.objectURI,value:h[0]})}continue}var m=d.current,y=d.context,b=!1,x=null,_=null,v=null,w=y.prefixes,k=!1,T=[],N=y.listMapping,I=!y.parent,S=y.language,j=y.vocabulary;r=this.parseURI(s(m.baseURI)),m.item=null;var R=m.getAttributeNode('vocab');if(R){var C=this.trim(R.value);if(0<C.length){j=C;var L=r.spec;this.addTriple(m,L,'http://www.w3.org/ns/rdfa#usesVocabulary',{type:e.objectURI,value:j})}else j=this.vocabulary}for(var O=0,i;O<m.attributes.length;O++)if(i=m.attributes[O],'x'===i.nodeName.charAt(0)&&0===i.nodeName.indexOf('xmlns:')){k||(w=this.copyMappings(w),k=!0);var E=i.nodeName.substring(6),D=e.trim(i.value);w[E]=this.options.base?p.join(D,this.options.base):D}var U=m.getAttributeNode('prefix');U&&(!k&&(w=this.copyMappings(w),k=!0),this.parsePrefixMappings(U.value,w));for(var A=null,P=0;!A&&P<this.langAttributes.length;P++)A=m.getAttributeNodeNS(this.langAttributes[P].namespaceURI,this.langAttributes[P].localName);if(A){var M=e.trim(A.value);S=0<M.length?M:null}var F=m.getAttributeNode('rel'),B=m.getAttributeNode('rev'),q=m.getAttributeNode('typeof'),H=m.getAttributeNode('property'),z=m.getAttributeNode('datatype'),V=this.inHTMLMode?m.getAttributeNode('datetime'):null,X=m.getAttributeNode('content'),W=m.getAttributeNode('about'),J=m.getAttributeNode('src'),Y=m.getAttributeNode('resource'),Q=m.getAttributeNode('href'),G=m.getAttributeNode('inlist'),K=[],Z,ee;if(F){ee=this.tokenize(F.value);for(var te=0;te<ee.length;te++)Z=this.parsePredicate(ee[te],j,y.terms,w,r,this.inHTMLMode&&null!==H),Z&&K.push(Z)}var ne=[];if(B){ee=this.tokenize(B.value);for(var ae=0;ae<ee.length;ae++)Z=this.parsePredicate(ee[ae],j,y.terms,w,r,this.inHTMLMode&&H),Z&&ne.push(Z)}if(this.inHTMLMode&&(F||B)&&H&&(0===K.length&&(F=null),0===ne.length&&(B=null)),F||B?(W&&(x=this.parseSafeCURIEOrCURIEOrURI(W.value,w,r)),q&&(v=x),!x&&(m.parentNode.nodeType===c.DOCUMENT_NODE?x=s(m.baseURI):y.parentObject&&(x=s(m.parentNode.baseURI)===y.parentObject?s(m.baseURI):y.parentObject)),Y&&(_=this.parseSafeCURIEOrCURIEOrURI(Y.value,w,r)),!_&&(Q?_=this.resolveAndNormalize(r,encodeURI(Q.value)):J?_=this.resolveAndNormalize(r,encodeURI(J.value)):q&&!W&&!(this.inXHTMLMode&&('head'===m.localName||'body'===m.localName))&&(_=this.newBlankNode())),q&&!W&&this.inXHTMLMode&&('head'===m.localName||'body'===m.localName)?v=x:q&&!W&&(v=_)):!H||X||z?(W&&(x=this.parseSafeCURIEOrCURIEOrURI(W.value,w,r)),!x&&Y&&(x=this.parseSafeCURIEOrCURIEOrURI(Y.value,w,r)),!x&&Q&&(x=this.resolveAndNormalize(r,encodeURI(Q.value))),!x&&J&&(x=this.resolveAndNormalize(r,encodeURI(J.value))),!x&&(m.parentNode.nodeType===c.DOCUMENT_NODE?x=s(m.baseURI):(this.inXHTMLMode||this.inHTMLMode)&&('head'===m.localName||'body'===m.localName)?x=s(m.parentNode.baseURI)===y.parentObject?s(m.baseURI):y.parentObject:q?x=this.newBlankNode():y.parentObject&&(x=s(m.parentNode.baseURI)===y.parentObject?s(m.baseURI):y.parentObject,!H&&(b=!0))),q&&(v=x)):(W&&(x=this.parseSafeCURIEOrCURIEOrURI(W.value,w,r),q&&(v=x)),x||m.parentNode.nodeType!==c.DOCUMENT_NODE?!x&&y.parentObject&&(x=s(m.parentNode.baseURI)===y.parentObject?s(m.baseURI):y.parentObject):(x=s(m.baseURI),q&&(v=x)),q&&!v&&(Y&&(v=this.parseSafeCURIEOrCURIEOrURI(Y.value,w,r)),!v&&Q&&(v=this.resolveAndNormalize(r,encodeURI(Q.value))),!v&&J&&(v=this.resolveAndNormalize(r,encodeURI(J.value))),!v&&(this.inXHTMLMode||this.inHTMLMode)&&('head'===m.localName||'body'===m.localName)&&(v=x),!v&&(v=this.newBlankNode()),_=v)),x&&(W||Y||v)){var re=x;q&&!W&&!Y&&_&&(re=_),this.newSubjectOrigin(m,re)}if(v){ee=this.tokenize(q.value);for(var oe=0,ie;oe<ee.length;oe++)ie=this.parseTermOrCURIEOrAbsURI(ee[oe],j,y.terms,w,r),ie&&this.addTriple(m,v,e.typeURI,{type:e.objectURI,value:ie})}if(x&&x!==y.parentObject&&(N={},I=!0),_){if(F&&G)for(var se=0,de;se<K.length;se++)de=N[K[se]],de||(de=[],N[K[se]]=de),de.push({type:e.objectURI,value:_});else if(F)for(var le=0;le<K.length;le++)this.addTriple(m,x,K[le],{type:e.objectURI,value:_});if(B)for(var pe=0;pe<ne.length;pe++)this.addTriple(m,_,ne[pe],{type:e.objectURI,value:x})}else{if(x&&!_&&(F||B)&&(_=this.newBlankNode()),F&&G)for(var ue=0,ce;ue<K.length;ue++)ce=N[K[ue]],ce||(ce=[],N[Z]=ce),T.push({predicate:K[ue],list:ce});else if(F)for(var he=0;he<K.length;he++)T.push({predicate:K[he],forward:!0});if(B)for(var fe=0;fe<ne.length;fe++)T.push({predicate:ne[fe],forward:!1})}if(H){var ge=null,me=null;z?(ge=''===z.value?e.PlainLiteralURI:this.parseTermOrCURIEOrAbsURI(z.value,j,y.terms,w,r),me=V&&!X?V.value:ge===e.XMLLiteralURI||ge===e.HTMLLiteralURI?null:X?X.value:m.textContent):X?(ge=e.PlainLiteralURI,me=X.value):V?(me=V.value,ge=e.deriveDateTimeType(me),!ge&&(ge=e.PlainLiteralURI)):!F&&!B&&(Y&&(me=this.parseSafeCURIEOrCURIEOrURI(Y.value,w,r)),!me&&Q?me=this.resolveAndNormalize(r,encodeURI(Q.value)):!me&&J&&(me=this.resolveAndNormalize(r,encodeURI(J.value))),me&&(ge=e.objectURI)),ge||(q&&!W?(ge=e.objectURI,me=v):(me=m.textContent,this.inHTMLMode&&'time'===m.localName&&(ge=e.deriveDateTimeType(me)),!ge&&(ge=e.PlainLiteralURI))),ee=this.tokenize(H.value);for(var ye=0,be;ye<ee.length;ye++)if(be=this.parsePredicate(ee[ye],j,y.terms,w,r),be)if(G){var xe=N[be];xe||(xe=[],N[be]=xe),xe.push(ge===e.XMLLiteralURI||ge===e.HTMLLiteralURI?{type:ge,value:m.childNodes}:{type:ge?ge:e.PlainLiteralURI,value:me,language:S})}else ge===e.XMLLiteralURI||ge===e.HTMLLiteralURI?this.addTriple(m,x,be,{type:ge,value:m.childNodes}):this.addTriple(m,x,be,{type:ge?ge:e.PlainLiteralURI,value:me,language:S})}if(x&&!b)for(var _e=0;_e<y.incomplete.length;_e++)y.incomplete[_e].list?y.incomplete[_e].list.push({type:e.objectURI,value:x}):y.incomplete[_e].forward?this.addTriple(m,y.subject,y.incomplete[_e].predicate,{type:e.objectURI,value:x}):this.addTriple(m,x,y.incomplete[_e].predicate,{type:e.objectURI,value:y.subject});var ve=null,we=x;b?(ve=this.push(y,y.subject),ve.parentObject=s(m.parentNode.baseURI)===y.parentObject?s(m.baseURI):y.parentObject,ve.incomplete=y.incomplete,ve.language=S,ve.prefixes=w,ve.vocabulary=j):(ve=this.push(y,x),ve.parentObject=_?_:x?x:y.subject,ve.prefixes=w,ve.incomplete=T,_&&(we=_,N={},I=!0),ve.listMapping=N,ve.language=S,ve.vocabulary=j),I&&o.unshift({parent:m,context:y,subject:we,listMapping:N});for(var ke=m.lastChild;ke;ke=ke.previousSibling)ke.nodeType===c.ELEMENT_NODE&&(ke.baseURI=m.baseURI,o.unshift({current:ke,context:ve}))}this.inHTMLMode&&this.copyProperties();for(var Te=0;Te<this.finishedHandlers.length;Te++)this.finishedHandlers[Te](n)}},{key:'push',value:function e(t,n){return{parent:t,subject:n?n:t?t.subject:null,parentObject:null,incomplete:[],listMapping:t?t.listMapping:{},language:t?t.language:this.language,prefixes:t?t.prefixes:this.target.graph.prefixes,terms:t?t.terms:this.target.graph.terms,vocabulary:t?t.vocabulary:this.vocabulary}}},{key:'resolveAndNormalize',value:function e(t,n){return p.join(n,t)}},{key:'setContext',value:function e(t){'html'===t.localName&&'XHTML+RDFa 1.1'===t.getAttribute('version')?this.setXHTMLContext():'html'===t.localName||'http://www.w3.org/1999/xhtml'===t.namespaceURI?'undefined'!=typeof document&&document.doctype?'-//W3C//DTD XHTML+RDFa 1.0//EN'===document.doctype.publicId&&'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd'===document.doctype.systemId?(console.log('WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode.'),this.setHTMLContext()):'-//W3C//DTD XHTML+RDFa 1.1//EN'===document.doctype.publicId&&'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd'===document.doctype.systemId?this.setXHTMLContext():this.setHTMLContext():this.setHTMLContext():this.setXMLContext()}},{key:'setHTMLContext',value:function e(){this.setInitialContext(),this.langAttributes=[{namespaceURI:'http://www.w3.org/XML/1998/namespace',localName:'lang'},{namespaceURI:null,localName:'lang'}],this.inXHTMLMode=!1,this.inHTMLMode=!0}},{key:'setInitialContext',value:function e(){this.vocabulary=null,this.langAttributes=[{namespaceURI:'http://www.w3.org/XML/1998/namespace',localName:'lang'}]}},{key:'setXHTMLContext',value:function e(){this.setInitialContext(),this.inXHTMLMode=!0,this.inHTMLMode=!1,this.langAttributes=[{namespaceURI:'http://www.w3.org/XML/1998/namespace',localName:'lang'},{namespaceURI:null,localName:'lang'}],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',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 e(){this.setInitialContext(),this.inXHTMLMode=!1,this.inHTMLMode=!1}},{key:'tokenize',value:function e(t){return this.trim(t).split(/\s+/)}},{key:'toRDFNodeObject',value:function t(n){if('undefined'!=typeof n){if('string'==typeof n)return'_:'===n.substring(0,2)?('undefined'==typeof this.blankNodes[n.substring(2)]&&(this.blankNodes[n.substring(2)]=new i(n.substring(2))),this.blankNodes[n.substring(2)]):d.namedNode(n);switch(n.type){case e.objectURI:return'_:'===n.value.substring(0,2)?('undefined'==typeof this.blankNodes[n.value.substring(2)]&&(this.blankNodes[n.value.substring(2)]=new i(n.value.substring(2))),this.blankNodes[n.value.substring(2)]):d.namedNode(n.value);case e.PlainLiteralURI:return new s(n.value,n.language||'');case e.XMLLiteralURI:case e.HTMLLiteralURI:var a='';return Object.keys(n.value).forEach(function(e){a+=u.domToString(n.value[e],this.htmlOptions)}),new s(a,'',new l(n.type));default:return new s(n.value,'',new l(n.type));}}}},{key:'trim',value:function e(t){return t.replace(/^\s\s*/,'').replace(/\s\s*$/,'')}}],[{key:'parseRDFaDOM',value:function t(n,a,r){var o=new e(a,{base:r});n.baseURI=r,o.process(n)}}]),e}();h.XMLLiteralURI='http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral',h.HTMLLiteralURI='http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML',h.PlainLiteralURI='http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral',h.objectURI='http://www.w3.org/1999/02/22-rdf-syntax-ns#object',h.typeURI='http://www.w3.org/1999/02/22-rdf-syntax-ns#type',h.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]',h.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_]',h.NCNAME=new RegExp('^'+h.nameStartChar+h.nameChar+'*$'),h.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'}],e.exports=h},function(e,t,n){var a=n(2),r=function e(t){var e={};e.ns={RDF:'http://www.w3.org/1999/02/22-rdf-syntax-ns#',RDFS:'http://www.w3.org/2000/01/rdf-schema#'},e.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},this.frameFactory=function(t,n,r){return{NODE:1,ARC:2,parent:n,parser:t,store:t.store,element:r,lastChild:0,base:null,lang:null,node:null,nodeType:null,listIndex:1,rdfid:null,datatype:null,collection:!1,terminateFrame:function e(){this.collection&&this.node.close()},addSymbol:function e(t,n){n=a.join(n,this.base),this.node=this.store.sym(n),this.nodeType=t},loadTriple:function t(){if(this.parent.parent.collection?this.parent.parent.node.append(this.node):this.store.add(this.parent.parent.node,this.parent.node,this.node,this.parser.why),null!=this.parent.rdfid){var n=this.store.sym(a.join('#'+this.parent.rdfid,this.base));this.store.add(n,this.store.sym(e.ns.RDF+'type'),this.store.sym(e.ns.RDF+'Statement'),this.parser.why),this.store.add(n,this.store.sym(e.ns.RDF+'subject'),this.parent.parent.node,this.parser.why),this.store.add(n,this.store.sym(e.ns.RDF+'predicate'),this.parent.node,this.parser.why),this.store.add(n,this.store.sym(e.ns.RDF+'object'),this.node,this.parser.why)}},isTripleToLoad:function e(){return null!=this.parent&&null!=this.parent.parent&&this.nodeType===this.NODE&&this.parent.nodeType===this.ARC&&this.parent.parent.nodeType===this.NODE},addNode:function e(t){this.addSymbol(this.NODE,t),this.isTripleToLoad()&&this.loadTriple()},addCollection:function e(){this.nodeType=this.NODE,this.node=this.store.collection(),this.collection=!0,this.isTripleToLoad()&&this.loadTriple()},addCollectionArc:function e(){this.nodeType=this.ARC},addBNode:function e(t){this.node=null==t?this.store.bnode():null==this.parser.bnodes[t]?this.parser.bnodes[t]=this.store.bnode():this.parser.bnodes[t],this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()},addArc:function t(n){n===e.ns.RDF+'li'&&(n=e.ns.RDF+'_'+this.parent.listIndex,this.parent.listIndex++),this.addSymbol(this.ARC,n)},addLiteral:function e(t){this.node=this.parent.datatype?this.store.literal(t,'',this.store.sym(this.parent.datatype)):this.store.literal(t,this.lang),this.nodeType=this.NODE,this.isTripleToLoad()&&this.loadTriple()}}},this.getAttributeNodeNS=function(e,t,n){var a=null;if(e.getAttributeNodeNS)a=e.getAttributeNodeNS(t,n);else for(var r=e.attributes,o=0,i,s;o<r.length;++o)if(i=r[o],i.namespaceURI===t&&(s=i.prefix?i.prefix+':'+n:n,s===i.nodeName)){a=i;break}return a},this.store=t,this.bnodes={},this.why=null,this.reify=!1,this.parse=function(t,n,a){var r=t.childNodes;this.cleanParser();var o;if(t.nodeType===e.nodeType.DOCUMENT){for(var i=0;i<r.length;i++)if(r[i].nodeType===e.nodeType.ELEMENT){o=r[i];break}}else if(t.nodeType===e.nodeType.ELEMENT)o=t;else throw new Error('RDFParser: can\'t find root in '+n+'. Halting. ');this.why=a;var s=this.frameFactory(this);return this.base=n,s.base=n,s.lang=null,this.parseDOM(this.buildFrame(s,o)),!0},this.parseDOM=function(t){for(var n=function(e){var t='';if(null==e.namespaceURI)throw new Error('RDF/XML syntax error: No namespace for '+e.localName+' in '+this.base);return e.namespaceURI&&(t+=e.namespaceURI),e.localName?t+=e.localName:e.nodeName&&(0<=e.nodeName.indexOf(':')?t+=e.nodeName.split(':')[1]:t+=e.nodeName),t}.bind(this),r=!0,o;t.parent;){var i=t.element,s=i.attributes;if(i.nodeType===e.nodeType.TEXT||i.nodeType===e.nodeType.CDATA_SECTION)t.parent.nodeType===t.NODE&&(t.addArc(e.ns.RDF+'value'),t=this.buildFrame(t)),t.addLiteral(i.nodeValue);else if(n(i)!==e.ns.RDF+'RDF')if(t.parent&&t.parent.collection&&(t.addCollectionArc(),t=this.buildFrame(t,t.element),t.parent.element=null),!t.parent||!t.parent.nodeType||t.parent.nodeType===t.ARC){var d=this.getAttributeNodeNS(i,e.ns.RDF,'about');if(o=this.getAttributeNodeNS(i,e.ns.RDF,'ID'),d&&o)throw new Error('RDFParser: '+i.nodeName+' has both rdf:id and rdf:about. Halting. Only one of these properties may be specified on a node.');if(!d&&o)t.addNode('#'+o.nodeValue),i.removeAttributeNode(o);else if(null==d&&null==o){var l=this.getAttributeNodeNS(i,e.ns.RDF,'nodeID');l?(t.addBNode(l.nodeValue),i.removeAttributeNode(l)):t.addBNode()}else t.addNode(d.nodeValue),i.removeAttributeNode(d);var p=this.getAttributeNodeNS(i,e.ns.RDF,'type');e.ns.RDF+'Description'!==n(i)&&(p={nodeValue:n(i)}),null!=p&&(this.store.add(t.node,this.store.sym(e.ns.RDF+'type'),this.store.sym(a.join(p.nodeValue,t.base)),this.why),p.nodeName&&i.removeAttributeNode(p));for(var u=s.length-1;0<=u;u--)this.store.add(t.node,this.store.sym(n(s[u])),this.store.literal(s[u].nodeValue,t.lang),this.why)}else{t.addArc(n(i)),this.reify&&(o=this.getAttributeNodeNS(i,e.ns.RDF,'ID'),o&&(t.rdfid=o.nodeValue,i.removeAttributeNode(o)));var c=this.getAttributeNodeNS(i,e.ns.RDF,'parseType'),h=this.getAttributeNodeNS(i,e.ns.RDF,'datatype');if(h&&(t.datatype=h.nodeValue,i.removeAttributeNode(h)),c){var g=c.nodeValue;'Literal'===g?(t.datatype=e.ns.RDF+'XMLLiteral',t=this.buildFrame(t),t.addLiteral(i.childNodes),r=!1):'Resource'===g?(t=this.buildFrame(t,t.element),t.parent.element=null,t.addBNode()):'Collection'===g&&(t=this.buildFrame(t,t.element),t.parent.element=null,t.addCollection()),i.removeAttributeNode(c)}if(0!==s.length){var m=this.getAttributeNodeNS(i,e.ns.RDF,'resource'),y=this.getAttributeNodeNS(i,e.ns.RDF,'nodeID');t=this.buildFrame(t),m?(t.addNode(m.nodeValue),i.removeAttributeNode(m)):y?(t.addBNode(y.nodeValue),i.removeAttributeNode(y)):t.addBNode();for(var b=s.length-1,x;0<=b;b--)x=this.buildFrame(t),x.addArc(n(s[b])),n(s[b])===e.ns.RDF+'type'?this.buildFrame(x).addNode(s[b].nodeValue):this.buildFrame(x).addLiteral(s[b].nodeValue)}else 0===i.childNodes.length&&this.buildFrame(t).addLiteral('')}for(i=t.element;t.parent;){for(var f=t;null==i;)t=t.parent,i=t.element;var _=i.childNodes&&i.childNodes[t.lastChild];if(!_||!r){if(t.terminateFrame(),!(t=t.parent))break;i=t.element,r=!0}else if(_.nodeType!==e.nodeType.ELEMENT&&_.nodeType!==e.nodeType.TEXT&&_.nodeType!==e.nodeType.CDATA_SECTION||(_.nodeType===e.nodeType.TEXT||_.nodeType===e.nodeType.CDATA_SECTION)&&1!==i.childNodes.length)t.lastChild++;else{t.lastChild++,t=this.buildFrame(f,i.childNodes[t.lastChild-1]);break}}}},this.cleanParser=function(){this.bnodes={},this.why=null},this.buildFrame=function(t,n){var r=this.frameFactory(this,t,n);if(t&&(r.base=t.base,r.lang=t.lang),!n||n.nodeType===e.nodeType.TEXT||n.nodeType===e.nodeType.CDATA_SECTION)return r;var o=n.attributes,i=n.getAttributeNode('xml:base');null!=i&&(r.base=i.nodeValue,n.removeAttribute('xml:base'));var s=n.getAttributeNode('xml:lang');null!=s&&(r.lang=s.nodeValue,n.removeAttribute('xml:lang'));for(var d=o.length-1;0<=d;d--)if('xml'===o[d].nodeName.substr(0,3)){if('xmlns:'===o[d].name.slice(0,6)){var l=o[d].nodeValue;this.base&&(l=a.join(l,this.base)),this.store.setPrefixForURI(o[d].name.slice(6),l)}n.removeAttributeNode(o[d])}return r}};e.exports=r},function(e,t,n){function a(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}var r=n(0),o=function e(){a(this,e)};o.boolean=new r('http://www.w3.org/2001/XMLSchema#boolean'),o.dateTime=new r('http://www.w3.org/2001/XMLSchema#dateTime'),o.decimal=new r('http://www.w3.org/2001/XMLSchema#decimal'),o.double=new r('http://www.w3.org/2001/XMLSchema#double'),o.integer=new r('http://www.w3.org/2001/XMLSchema#integer'),o.langString=new r('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString'),o.string=new r('http://www.w3.org/2001/XMLSchema#string'),e.exports=o},function(e,t,n){function a(e,t){var n=s.Parser(),a=s.Writer({format:'N-Quads'}),r;o.waterfall([function(t){n.parse(e,t)},function(e,t,n){null!==e&&a.addTriple(e),'function'==typeof n&&a.end(n)},function(e,t){try{i.fromRDF(e,{format:'application/nquads'},t)}catch(e){t(e)}},function(e,n){r=JSON.stringify(e),t(null,r)}],function(e,n){t(e,r)})}function r(e,t){var n=s.Parser(),a=s.Writer({format:'N-Quads'}),r;o.waterfall([function(t){n.parse(e,t)},function(e,t,n){null!==e&&a.addTriple(e),'function'==typeof n&&a.end(n)},function(e,n){r=e,t(null,r)}],function(e,n){t(e,r)})}e.exports.convertToJson=a,e.exports.convertToNQuads=r;var o=n(61),i=n(39),s=n(42)},function(e,t,n){(function(a,o,i,s){var d,l;/** +"undefined"!=typeof window&&(window.solid||(window.solid={}),window.solid.auth||(window.solid.auth={fetch:(e,t)=>window.fetch(e,t)})),function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("window"),require("null"),require("solid-auth-client")):"function"==typeof define&&define.amd?define(["window","null"],t):"object"==typeof exports?exports.$rdf=t(require("window"),require("null"),require("solid-auth-client")):e.$rdf=t(e.window,e.null,e.solid.auth)}(window,function(e,t,n){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=59)}([function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var u=n(10),l=n(1),c=function(e){function t(e){var n;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=o(this,a(t).call(this))).termType=t.termType,e&&e.termType===t.termType&&(e=e.value),!e)throw new Error("Missing IRI for NamedNode");if(!e.includes(":"))throw new Error('NamedNode IRI "'+e+'" must be absolute.');if(e.includes(" "))throw new Error('Error: NamedNode IRI "'+e+'" must not contain unencoded spaces.');return n.value=e,n}var n,r,u;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(t,l),n=t,u=[{key:"fromValue",value:function(e){return null==e?e:e&&e.termType?e:new t(e)}}],(r=[{key:"dir",value:function(){var e=this.uri.split("#")[0],n=e.slice(0,-1).lastIndexOf("/"),r=e.indexOf("//");return r>=0&&n<r+2||n<0?null:new t(e.slice(0,n+1))}},{key:"site",value:function(){var e=this.uri.split("#")[0],n=e.indexOf("//");if(n<0)throw new Error("This URI does not have a web site part (origin)");var r=e.indexOf("/",n+2);if(r<0)throw new Error("This URI does not have a web site part. (origin)");return new t(e.slice(0,r+1))}},{key:"doc",value:function(){return this.uri.indexOf("#")<0?this:new t(this.uri.split("#")[0])}},{key:"toString",value:function(){return"<"+this.uri+">"}},{key:"uri",get:function(){return this.value},set:function(e){this.value=e}}])&&i(n.prototype,r),u&&i(n,u),t}();c.termType="NamedNode",c.prototype.classOrder=u.NamedNode,c.prototype.isVar=0,e.exports=c},function(e,t,n){"use strict";function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var i=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,n,i;return t=e,(n=[{key:"substitute",value:function(e){return console.log("@@@ node substitute"+this),this}},{key:"compareTerm",value:function(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.value<e.value?-1:this.value>e.value?1:0}},{key:"equals",value:function(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}},{key:"hashString",value:function(){return this.toCanonical()}},{key:"sameTerm",value:function(e){return this.equals(e)}},{key:"toCanonical",value:function(){return this.toNT()}},{key:"toNT",value:function(){return this.toString()}},{key:"toString",value:function(){throw new Error("Node.toString() is abstract - see the subclasses instead")}}])&&r(t.prototype,n),i&&r(t,i),e}();e.exports=i,i.fromValue=function(e){var t=n(18),r=n(11);n(0);return null==e?e:e&&e.termType?e:Array.isArray(e)?new t(e):r.fromValue(e)};var o={xsd:n(12)("http://www.w3.org/2001/XMLSchema#")};i.toJS=function(e){if(e.elements)return e.elements.map(i.toJS);if(!e.datatype)return e;if(e.datatype.sameTerm(o.xsd("boolean")))return"1"===e.value;if(e.datatype.sameTerm(o.xsd("dateTime"))||e.datatype.sameTerm(o.xsd("date")))return new Date(e.value);if(e.datatype.sameTerm(o.xsd("integer"))||e.datatype.sameTerm(o.xsd("float"))||e.datatype.sameTerm(o.xsd("decimal"))){Number(e.value);return Number(e.value)}return e.value}},function(e,t,n){var r=r||console.log;e.exports.docpart=o,e.exports.document=function(e){return new i(o(e.uri))},e.exports.hostpart=function(e){var t=/[^\/]*\/\/([^\/]*)\//.exec(e);return t?t[1]:""},e.exports.join=function(e,t){var n,i,o,a,s,u=t.indexOf("#");u>0&&(t=t.slice(0,u));if(0===e.length)return t;if(0===e.indexOf("#"))return t+e;if(e.indexOf(":")>=0)return e;if(n=t.indexOf(":"),0===t.length)return e;if(n<0)return r("Invalid base: "+t+" in join with given: "+e),e;if(i=t.slice(0,+n+1||9e9),0===e.indexOf("//"))return i+e;if(t.indexOf("//",n)===n+1){if((o=t.indexOf("/",n+3))<0)return t.length-n-3>0?t+"/"+e:i+e}else if((o=t.indexOf("/",n+1))<0)return t.length-n-1>0?t+"/"+e:i+e;if(0===e.indexOf("/"))return t.slice(0,o)+e;if(s=t.slice(o),(a=s.lastIndexOf("/"))<0)return i+e;a>=0&&a<s.length-1&&(s=s.slice(0,+a+1||9e9));s+=e;for(;s.match(/[^\/]*\/\.\.\//);)s=s.replace(/[^\/]*\/\.\.\//,"");return s=(s=s.replace(/\.\//g,"")).replace(/\/\.$/,"/"),t.slice(0,o)+s},e.exports.protocol=function(e){var t;return(t=e.indexOf(":"))<0?null:e.slice(0,t)},e.exports.refTo=function(e,t){var n,r,i,o,a,s,u,l,c,f,h,d,p=new RegExp("^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$");if(!e)return t;if(e===t)return"";for(n=u=0,o=t.length;u<o&&t[n]===e[n];n=++u);if(e.slice(0,n).match(p)&&((r=t.indexOf("//"))<0&&(r=-2),i=t.indexOf("/",r+2),"/"!==t[i+1]&&"/"!==e[i+1]&&t.slice(0,i)===e.slice(0,i)))return t.slice(i);if("#"===t[n]&&e.length===n)return t.slice(n);for(;n>0&&"/"!==t[n-1];)n--;if(n<3)return t;if(e.indexOf("//",n-2)>0||t.indexOf("//",n-2)>0)return t;if(e.indexOf(":",n)>0)return t;for(s=0,f=e.slice(n),l=0,a=f.length;l<a;l++)"/"===f[l]&&s++;if(0===s&&n<t.length&&"#"===t[n])return"./"+t.slice(n);if(0===s&&n===t.length)return"./";if(d="",s>0)for(c=1,h=s;h>=1?c<=h:c>=h;h>=1?++c:--c)d+="../";return d+t.slice(n)};var i=n(0);function o(e){var t;return(t=e.indexOf("#"))<0?e:e.slice(0,t)}},function(e,t,n){(function(e){var t=n(2).docpart,r=n(9),i=n(0);function o(e,t,n,r){var i,a="",s=[!1];if(void 0===e.nodeType)return a;if(1===e.nodeType){if(e.hasAttribute("class")&&"classWithChildText"in t&&e.matches(t.classWithChildText.class))a+=e.querySelector(t.classWithChildText.element).textContent;else if(!("skipNodeWithClass"in t&&e.matches("."+t.skipNodeWithClass))){var u=e.nodeName.toLowerCase();a+="<"+u;var l=[];for(i=e.attributes.length-1;i>=0;i--){var c=e.attributes[i];if(!(r.length>0&&r[c.name])&&!/^\d+$/.test(c.name)){if("class"===c.name&&"replaceClassItemWith"in t&&c.value.split(" ").indexOf(t.replaceClassItemWith.source)>-1){var f=new RegExp(t.replaceClassItemWith.source,"g");c.value=c.value.replace(f,t.replaceClassItemWith.target).trim()}"class"===c.name&&"skipClassWithValue"in t&&t.skipClassWithValue===c.value||l.push(c.name+"='"+c.value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,""")+"'")}}if(l.length>0&&("sortAttributes"in t&&t.sortAttributes&&l.sort(function(e,t){return e.toLowerCase().localeCompare(t.toLowerCase())}),a+=" "+l.join(" ")),n[u])a+=" />";else{for(a+=">",a+="html"===u?"\n ":"",s.push("style"===u||"script"===u),i=0;i<e.childNodes.length;i++)a+=o(e.childNodes[i]);s.pop(),a+="body"===u?"</"+u+">\n":"</"+u+">"}}}else if(8===e.nodeType)a+="\x3c!--"+e.nodeValue+"--\x3e";else if(3===e.nodeType||4===e.nodeType){var h=e.nodeValue.replace(/\n+$/,"");a+=s[s.length-1]?h:h.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}else console.log("Warning; Cannot handle serialising nodes of type: "+e.nodeType),console.log(e);return a}function a(e,t,n,r){var i=function(e){return"BlankNode"===e.termType?null:e},o=function(e){var t=n.statementsMatching(e).map(function(e){return i(e.subject)+" "+i(e.predicate)+" "+i(e.object)}).concat(n.statementsMatching(void 0,void 0,e).map(function(e){return i(e.subject)+" "+i(e.predicate)+" "+i(e.object)}));return t.sort(),t.join("\n")};return"BlankNode"===e.termType&&"BlankNode"===t.termType?0===e.compareTerm(t)?0:o(e)>o(t)?1:o(e)<o(t)?-1:e.compareTerm(t):r&&e.uri&&t.uri?(r[e.uri]||e.uri).localeCompare(r[t.uri]||t.uri):e.compareTerm(t)}function s(e,t){return e.slice(0,t.length)===t}e.exports.AJAR_handleNewTerm=function(e,n,i){var o=null;if(void 0===e.fetcher)return;o=e.fetcher;if("NamedNode"!==n.termType)return;var a,u=t(n.uri);if(n.uri.indexOf("#")<0){if(s(n.uri,"http://dbpedia.org/resource/Category:"))return;s(n.uri,"http://purl.org/dc/elements/1.1/")||s(n.uri,"http://purl.org/dc/terms/")?a="http://dublincore.org/2005/06/13/dcq":s(n.uri,"http://xmlns.com/wot/0.1/")?a="http://xmlns.com/wot/0.1/index.rdf":s(n.uri,"http://web.resource.org/cc/")&&(a="http://web.resource.org/cc/schema.rdf")}a&&(u=a);if(o&&"unrequested"!==o.getState(u))return;a&&r.warn("Assuming server still broken, faking redirect of <"+n.uri+"> to <"+u+">");return o.fetch(u,{referringTerm:i})},e.exports.ArrayIndexOf=function(e,t,n){n||(n=0);var r=e.length;n<0&&(n=r+n);for(;n<r;n++)if(e[n]===t)return n;return-1},e.exports.callbackify=function(e,t){e.callbacks={};for(var n=t.length-1;n>=0;n--)e.callbacks[t[n]]=[];e.addHook=function(t){e.callbacks[t]||(e.callbacks[t]=[])},e.addCallback=function(t,n){e.callbacks[t].push(n)},e.removeCallback=function(t,n){for(var r=0;r<e.callbacks[t].length;r++)if(e.callbacks[t][r].name===n)return e.callbacks[t].splice(r,1),!0;return!1},e.insertCallback=function(t,n){e.callbacks[t].unshift(n)},e.fireCallbacks=function(t,n){var r,i,o=[],a=[],s=e.callbacks[t].length;for(r=s-1;r>=0;r--)(i=e.callbacks[t][r])&&i.apply(e,n)&&o.push(i);for(r=o.length-1;r>=0;r--)a.push(o[r]);for(r=s;r<e.callbacks[t].length;r++)a.push(e.callbacks[t][r]);e.callbacks[t]=a}},e.exports.dtstamp=function(){var e=new Date,t=e.getYear()+1900,n=e.getMonth()+1,r=e.getDate(),i=e.getUTCHours(),o=e.getUTCMinutes(),a=e.getSeconds();n<10&&(n="0"+n);r<10&&(r="0"+r);i<10&&(i="0"+i);o<10&&(o="0"+o);a<10&&(a="0"+a);return t+"-"+n+"-"+r+"T"+i+":"+o+":"+a+"Z"},e.exports.DOMParserFactory=function(){return window.DOMParser?new DOMParser:!!window.ActiveXObject&&new ActiveXObject("Microsoft.XMLDOM")},e.exports.domToString=function(e,t){var n=[];"selfClosing"in(t=t||{})&&t.selfClosing.split(" ").forEach(function(e){n[e]=!0});var r=[];"skipAttributes"in t&&t.skipAttributes.split(" ").forEach(function(e){r[e]=!0});return o(e,t,n,r)},e.exports.dumpNode=o,e.exports.heavyCompare=a,e.exports.heavyCompareSPO=function(e,t,n,r){return a(e.subject,t.subject,n,r)||a(e.predicate,t.predicate,n,r)||a(e.object,t.object,n,r)},e.exports.output=function(e){var t=document.createElement("div");t.textContent=e,document.body.appendChild(t)},e.exports.parseXML=function(t,r){var i;if(r=r||{},e&&e.exports){var o=n(41).DOMParser,a=(new o).parseFromString(t,r.contentType||"application/xhtml+xml");return a}i="undefined"!=typeof window&&window.DOMParser?new window.DOMParser:new o;return i.parseFromString(t,"application/xml")},e.exports.RDFArrayRemove=function(e,t){for(var n=0;n<e.length;n++)if(e[n].subject.sameTerm(t.subject)&&e[n].predicate.sameTerm(t.predicate)&&e[n].object.sameTerm(t.object)&&e[n].why.sameTerm(t.why))return void e.splice(n,1);throw new Error("RDFArrayRemove: Array did not contain "+t+" "+t.why)},e.exports.stackString=function(e){var t=e+"\n";if(!e.stack)return t+"No stack available.\n";for(var n=e.stack.toString().split("\n"),r=[],i=0;i<n.length;i++){var o=n[i];if(o.indexOf("ecmaunit.js")>-1)break;"("==o.charAt(0)&&(o="function"+o);var a=o.split("@");r.push(a)}for(var i=0;i<r.length;i++)t+=" "+r[i][1]+"\n "+r[i][0];return t},e.exports.string_startswith=s,e.exports.string={},e.exports.string.template=function(e,t){for(var n=e.split("%s"),r="",i=0;i<t.length;i++)t[i]+="",r+=n[i]+t[i];return r+n.slice(t.length).join()},e.exports.uri=n(2),e.exports.log=r,e.exports.mediaTypeClass=function(e){return e=e.split(";")[0].trim(),new i("http://www.w3.org/ns/iana/media-types/"+e+"#Resource")},e.exports.linkRelationProperty=function(e){return new i("http://www.w3.org/ns/iana/link-relations/relation#"+e.trim())}}).call(this,n(79)(e))},function(e,t){var n,r,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var u,l=[],c=!1,f=-1;function h(){c&&u&&(c=!1,u.length?l=u.concat(l):f=-1,l.length&&d())}function d(){if(!c){var e=s(h);c=!0;for(var t=l.length;t;){for(u=l,l=[];++f<t;)u&&u[f].run();f=-1,t=l.length}u=null,c=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function v(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new p(e,t)),1!==l.length||c||s(d)},p.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=v,i.addListener=v,i.once=v,i.off=v,i.removeListener=v,i.removeAllListeners=v,i.emit=v,i.prependListener=v,i.prependOnceListener=v,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var u=n(10),l=n(1),c=function(e){function t(e){var n;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=o(this,a(t).call(this))).termType=t.termType,e){if("string"!=typeof e)throw console.log("Bad blank id:",e),new Error("Bad id argument to new blank node: "+e);if(e.includes("#")){var r=e.split("#");e=r[r.length-1]}n.id=e}else n.id="n"+t.nextId++;return n.value=n.id,n}var n,r,u;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(t,l),n=t,(r=[{key:"compareTerm",value:function(e){return this.classOrder<e.classOrder?-1:this.classOrder>e.classOrder?1:this.id<e.id?-1:this.id>e.id?1:0}},{key:"copy",value:function(e){var n=new t;return e.copyTo(this,n),n}},{key:"toCanonical",value:function(){return"_:"+this.value}},{key:"toString",value:function(){return t.NTAnonymousNodePrefix+this.id}}])&&i(n.prototype,r),u&&i(n,u),t}();c.nextId=0,c.termType="BlankNode",c.NTAnonymousNodePrefix="_:",c.prototype.classOrder=u.BlankNode,c.prototype.isBlank=1,c.prototype.isVar=1,e.exports=c},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){"use strict";var r=n(19),i=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=f;var o=n(15);o.inherits=n(7);var a=n(46),s=n(30);o.inherits(f,a);for(var u=i(s.prototype),l=0;l<u.length;l++){var c=u[l];f.prototype[c]||(f.prototype[c]=s.prototype[c])}function f(e){if(!(this instanceof f))return new f(e);a.call(this,e),s.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",h)}function h(){this.allowHalfOpen||this._writableState.ended||r.nextTick(d,this)}function d(e){e.end()}Object.defineProperty(f.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(f.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),f.prototype._destroy=function(e,t){this.push(null),this.end(),r.nextTick(t,e)}},function(e,t){e.exports={debug:function(e){},warn:function(e){},info:function(e){},error:function(e){},success:function(e){},msg:function(e){}}},function(e,t){e.exports={Literal:1,Collection:3,Graph:4,NamedNode:5,BlankNode:6,Variable:7}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var u=n(10),l=n(0),c=n(1),f=n(37),h=function(e){function t(e,n,r){var i;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(i=o(this,a(t).call(this))).termType=t.termType,i.value=e,n&&(i.lang=n,r=f.langString),r&&(i.datatype=l.fromValue(r)),i}var n,u,h;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(t,c),n=t,h=[{key:"fromBoolean",value:function(e){return new t(e?"1":"0",null,f.boolean)}},{key:"fromDate",value:function(e){if(!(e instanceof Date))throw new TypeError("Invalid argument to Literal.fromDate()");var n=function(e){return(""+(100+e)).slice(1,3)};return new t(e.getUTCFullYear()+"-"+n(e.getUTCMonth()+1)+"-"+n(e.getUTCDate())+"T"+n(e.getUTCHours())+":"+n(e.getUTCMinutes())+":"+n(e.getUTCSeconds())+"Z",null,f.dateTime)}},{key:"fromNumber",value:function(e){if("number"!=typeof e)throw new TypeError("Invalid argument to Literal.fromNumber()");var n,r=e.toString();return n=r.indexOf("e")<0&&Math.abs(e)<=Number.MAX_SAFE_INTEGER?Number.isInteger(e)?f.integer:f.decimal:f.double,new t(r,null,n)}},{key:"fromValue",value:function(e){if(null==e)return e;if("object"===r(e)&&e.termType)return e;switch(r(e)){case"object":if(e instanceof Date)return t.fromDate(e);case"boolean":return t.fromBoolean(e);case"number":return t.fromNumber(e);case"string":return new t(e)}throw new Error("Can't make literal from "+e+" of type "+r(e))}}],(u=[{key:"copy",value:function(){return new t(this.value,this.lang,this.datatype)}},{key:"equals",value:function(e){return!!e&&(this.termType===e.termType&&this.value===e.value&&this.language===e.language&&(!this.datatype&&!e.datatype||this.datatype&&this.datatype.equals(e.datatype)))}},{key:"toNT",value:function(){if("number"==typeof this.value)return this.toString();if("string"!=typeof this.value)throw new Error("Value of RDF literal is not string or number: "+this.value);var e=this.value;return e='"'+(e=(e=(e=e.replace(/\\/g,"\\\\")).replace(/\"/g,'\\"')).replace(/\n/g,"\\n"))+'"',this.language?e+="@"+this.language:this.datatype.equals(f.string)||(e+="^^"+this.datatype.toCanonical()),e}},{key:"toString",value:function(){return""+this.value}},{key:"language",get:function(){return this.lang},set:function(e){this.lang=e||""}}])&&i(n.prototype,u),h&&i(n,h),t}();h.termType="Literal",h.prototype.classOrder=u.Literal,h.prototype.datatype=f.string,h.prototype.lang="",h.prototype.isVar=0,e.exports=h},function(e,t,n){var r=n(0);e.exports=function(e){return function(t){return new r(e+(t||""))}}},function(e,t){},function(e,t,n){(function(e){var r=void 0!==e&&e||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new o(i.call(setTimeout,r,arguments),clearTimeout)},t.setInterval=function(){return new o(i.call(setInterval,r,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(r,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(62),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(5))},function(e,t,n){(function(e){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=e.isBuffer}).call(this,n(49).Buffer)},function(e,t,n){function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var u=n(3).ArrayIndexOf,l=n(55),c=n(3).RDFArrayRemove,f=n(22),h=n(1),d=n(23);function p(e,t,n,r){var i=e.any(t,n,void 0);return!!i&&(e.equate(i,r),!0)}function v(e,t,n,r){var i=e.any(void 0,n,r);return!!i&&(e.equate(i,t),!0)}function y(e,t,n,r,i){e.typeCallback&&e.typeCallback(e,r,i);var o=e.classActions[r.hashString()],a=!1;if(o)for(var s=0;s<o.length;s++)a=a||o[s](e,t,n,r,i);return a}var g=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=o(this,a(t).call(this))).propertyActions=[],n.classActions=[],n.redirections=[],n.aliases=[],n.HTTPRedirects=[],n.subjectIndex=[],n.predicateIndex=[],n.objectIndex=[],n.whyIndex=[],n.index=[n.subjectIndex,n.predicateIndex,n.objectIndex,n.whyIndex],n.namespaces={},n.features=e||["sameAs","InverseFunctionalProperty","FunctionalProperty"],n.initPropertyActions(n.features),n}var r,g,m;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(t,l),r=t,m=[{key:"defaultGraphURI",get:function(){return"chrome:theSession"}}],(g=[{key:"substitute",value:function(e){var n=this.statements.map(function(t){return t.substitute(e)}),r=new t;return r.add(n),r}},{key:"applyPatch",value:function(e,t,r){var i,o=n(17).Query,a=this,s=null;function u(n){if(e.delete){i=e.delete,s&&(i=i.substitute(s)),i=i.statements;var o=[],u=i.map(function(e){var n=a.statementsMatching(e.subject,e.predicate,e.object,t);return 0===n.length?(o.push(e),null):n[0]});if(o.length)return r("Could not find to delete: "+o.join("\n or "));u.map(function(e){a.remove(e)})}e.insert&&(i=e.insert,s&&(i=i.substitute(s)),(i=i.statements).map(function(e){e.why=t,a.add(e.subject,e.predicate,e.object,e.why)})),n()}if(e.where){var l=new o("patch");l.pat=e.where,l.pat.statements.map(function(e){e.why=t}),l.sync=!0;var c=[];a.query(l,function(e){c.push(e)},a.fetcher,function(){return 0===c.length?r("No match found to be patched:"+e.where):c.length>1?r("Patch ambiguous. No patch done."):(s=c[0],void u(r))})}else u(r)}},{key:"declareExistential",value:function(e){return this._existentialVariables||(this._existentialVariables=[]),this._existentialVariables.push(e),e}},{key:"initPropertyActions",value:function(e){this.propertyActions["<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"]=[y],u(e,"sameAs")>=0&&(this.propertyActions["<http://www.w3.org/2002/07/owl#sameAs>"]=[function(e,t,n,r,i){return e.equate(t,r),!0}]),u(e,"InverseFunctionalProperty")>=0&&(this.classActions["<http://www.w3.org/2002/07/owl#InverseFunctionalProperty>"]=[function(e,t,n,r,i){return e.newPropertyAction(t,v)}]),u(e,"FunctionalProperty")>=0&&(this.classActions["<http://www.w3.org/2002/07/owl#FunctionalProperty>"]=[function(e,t,n,r,i){return e.newPropertyAction(t,p)}])}},{key:"add",value:function(e,n,r,i){var o,a,s;if(1===arguments.length){if(e instanceof Array)for(o=0;o<e.length;o++)this.add(e[o]);else e instanceof f?this.add(e.subject,e.predicate,e.object,e.why):e instanceof t&&this.add(e.statements);return this}i||(i=this.fetcher?this.fetcher.appNode:this.sym("chrome:theSession")),e=h.fromValue(e),n=h.fromValue(n),r=h.fromValue(r),i=h.fromValue(i),this.predicateCallback&&this.predicateCallback(this,n,i);var u=this.canon(n).hashString(),l=!1;if(a=this.propertyActions[u])for(o=0;o<a.length;o++)l=l||a[o](this,e,n,r,i);if(this.holds(e,n,r,i))return null;var c=[this.canon(e).hashString(),u,this.canon(r).hashString(),this.canon(i).hashString()];for(s=new f(e,n,r,i),o=0;o<4;o++){var d=this.index[o],p=c[o];d[p]||(d[p]=[]),d[p].push(s)}return this.statements.push(s),s}},{key:"canon",value:function(e){if(!e)return e;var t=this.redirections[e.hashString()];return t||e}},{key:"check",value:function(){this.checkStatementList(this.statements);for(var e=0;e<4;e++){var t=this.index[e];for(var n in t)t.hasOwnProperty(n)&&this.checkStatementList(t[n],e)}}},{key:"checkStatementList",value:function(e,t){for(var n,r=" found in "+["subject","predicate","object","why"][t]+" index.",i=0;i<e.length;i++){for(var o=[(n=e[i]).subject,n.predicate,n.object,n.why],a=function(e,t){for(var n=0;n<e.length;n++)if(e[n].subject.sameTerm(t.subject)&&e[n].predicate.sameTerm(t.predicate)&&e[n].object.sameTerm(t.object)&&e[n].why.sameTerm(t.why))return!0},s=0;s<4;s++){var u=this.canon(o[s]).hashString();this.index[s][u]&&a(this.index[s][u],n)}if(!a(this.statements,n))throw new Error("Statement list does not statement "+n+"@"+n.why+r)}}},{key:"close",value:function(){return this}},{key:"copyTo",value:function(e,t,n){n||(n=[]);var r=this.statementsMatching(e);-1!==u(n,"two-direction")&&r.concat(this.statementsMatching(void 0,void 0,e));for(var i=0;i<r.length;i++){var o=r[i];switch(o.object.termType){case"NamedNode":this.add(t,o.predicate,o.object);break;case"Literal":case"BlankNode":case"Collection":this.add(t,o.predicate,o.object.copy(this))}-1!==u(n,"delete")&&this.remove(o)}}},{key:"equate",value:function(e,t){e=this.canon(e),t=this.canon(t);var n=e.compareTerm(t);return!n||(n<0?this.replaceWith(t,e):this.replaceWith(e,t))}},{key:"formula",value:function(e){return new t(e)}},{key:"match",value:function(e,t,n,r){return this.statementsMatching(h.fromValue(e),h.fromValue(t),h.fromValue(n),h.fromValue(r))}},{key:"mentionsURI",value:function(e){var t="<"+e+">";return!!this.subjectIndex[t]||!!this.objectIndex[t]||!!this.predicateIndex[t]}},{key:"newExistential",value:function(e){if(!e)return this.bnode();var t=this.sym(e);return this.declareExistential(t)}},{key:"newPropertyAction",value:function(e,t){var n=e.hashString();this.propertyActions[n]||(this.propertyActions[n]=[]),this.propertyActions[n].push(t);for(var r=this.statementsMatching(void 0,e,void 0),i=!1,o=0;o<r.length;o++)i=i||t(this,r[o].subject,e,r[o].object);return i}},{key:"newUniversal",value:function(e){var t=this.sym(e);return this._universalVariables||(this._universalVariables=[]),this._universalVariables.push(t),t}},{key:"variable",value:function(e){return new d(e)}},{key:"nextSymbol",value:function(e){for(var t=0;;t++){var n=e.uri+"#n"+t;if(!this.mentionsURI(n))return this.sym(n)}}},{key:"query",value:function(e,t,r,i){return n(17).indexedFormulaQuery.call(this,e,t,r,i)}},{key:"querySync",value:function(e){var t=[],r=!1;if(e.sync=!0,n(17).indexedFormulaQuery.call(this,e,function(e){t.push(e)},null,function(){r=!0}),!r)throw new Error("Sync query should have called done function");return t}},{key:"remove",value:function(e){if(e instanceof Array){for(var n=0;n<e.length;n++)this.remove(e[n]);return this}if(e instanceof t)return this.remove(e.statements);var r=this.statementsMatching(e.subject,e.predicate,e.object,e.why);if(!r.length)throw new Error("Statement to be removed is not on store: "+e);return this.removeStatement(r[0]),this}},{key:"removeDocument",value:function(e){for(var t=this.statementsMatching(void 0,void 0,void 0,e).slice(),n=0;n<t.length;n++)this.removeStatement(t[n]);return this}},{key:"removeMany",value:function(e,t,n,r,i){for(var o=this.statementsMatching(e,t,n,r,!1),a=[],s=0;s<o.length;s++)a.push(o[s]);for(i&&(a=a.slice(0,i)),s=0;s<a.length;s++)this.remove(a[s])}},{key:"removeMatches",value:function(e,t,n,r){return this.removeStatements(this.statementsMatching(e,t,n,r)),this}},{key:"removeStatement",value:function(e){for(var t=[e.subject,e.predicate,e.object,e.why],n=0;n<4;n++){var r=this.canon(t[n]).hashString();this.index[n][r]&&c(this.index[n][r],e)}return c(this.statements,e),this}},{key:"removeStatements",value:function(e){for(var t=0;t<e.length;t++)this.remove(e[t]);return this}},{key:"replaceWith",value:function(e,t){for(var n=e.hashString(),r=t.hashString(),i=function(e){var t=e[n];if(t){var i=e[r];e[r]=i?t.concat(i):t,delete e[n]}},o=0;o<4;o++)i(this.index[o]);if(this.redirections[n]=t,e.uri){if(this.aliases[r]||(this.aliases[r]=[]),this.aliases[r].push(e),this.aliases[n])for(o=0;o<this.aliases[n].length;o++)this.redirections[this.aliases[n][o].hashString()]=t,this.aliases[r].push(this.aliases[n][o]);this.add(t,this.sym("http://www.w3.org/2007/ont/link#uri"),e.uri),this.fetcher&&this.fetcher.nowKnownAs(e,t)}return i(this.classActions),i(this.propertyActions),!0}},{key:"allAliases",value:function(e){var t=this.aliases[this.canon(e).hashString()]||[];return t.push(this.canon(e)),t}},{key:"sameThings",value:function(e,t){if(e.sameTerm(t))return!0;var n=this.canon(e);if(!n)return!1;var r=this.canon(t);return!!r&&n.uri===r.uri}},{key:"setPrefixForURI",value:function(e,t){"tab"===e&&this.namespaces.tab||"ns"!==e.slice(0,2)&&"default"!==e.slice(0,7)&&(this.namespaces[e]=t)}},{key:"statementsMatching",value:function(e,t,n,r,i){var o,a,s=[e,t,n,r],u=[],l=[],c=[],f=[];for(o=0;o<4;o++)u[o]=this.canon(h.fromValue(s[o])),u[o]?(f.push(o),l[o]=u[o].hashString()):c.push(o);if(0===f.length)return this.statements;if(1===f.length)return o=f[0],(a=this.index[o][l[o]])&&i&&a.length>1&&(a=a.slice(0,1)),a=a||[];var d,p,v=1e10;for(p=0;p<f.length;p++){if(o=f[p],!(a=this.index[o][l[o]]))return[];a.length<v&&(v=a.length,d=p)}for(var y=f[d],g=this.index[y][l[y]],m=f.slice(0,d).concat(f.slice(d+1)),b=[],w=["subject","predicate","object","why"],x=0;x<g.length;x++){var _=g[x];for(p=0;p<m.length;p++)if(o=m[p],!this.canon(_[w[o]]).sameTerm(u[o])){_=null;break}if(null!=_&&(b.push(_),i))break}return b}},{key:"uris",value:function(e){var t=this.canon(e),n=this.aliases[t.hashString()];if(!t.uri)return[];var r=[t.uri];if(n)for(var i=0;i<n.length;i++)r.push(n[i].uri);return r}},{key:"length",get:function(){return this.statements.length}}])&&i(r.prototype,g),m&&i(r,m),t}();e.exports=g,g.handleRDFType=y},function(e,t,n){var r=n(16),i=n(9),o=n(2).docpart,a=r.defaultGraphURI;e.exports.Query=function e(t,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.pat=new r,this.vars=[],this.name=t,this.id=n},e.exports.indexedFormulaQuery=function(e,t,n,r){function s(e){var t,n="";for(t in e)e.hasOwnProperty(t)&&(n+=" "+t+" -> "+e[t]);return n}function u(e){var t,n="Bindings: ",r=e.length;for(t=0;t<r;t++)n+=s(e[t][0])+";\n\t";return n}function l(e,t,n,r){var i;if(e.length!==t.length)return[];if(!e.length)return[[[],null]];var o=function(e,t,n,r){var i=n[e];if(void 0===i){if(e.isVar){var o=[];return o[e]=t,[[o,null]]}i=e}if(!i.complexType)return r.redirections[i]&&(i=r.redirections[i]),r.redirections[t]&&(t=r.redirections[t]),i.sameTerm(t)||i.uri&&i.uri===a?[[[],null]]:[];if(e instanceof Array)return t instanceof Array?l(e,t,n):[];throw new Error("query.js: oops - code not written yet")}(e[0],t[0],n,r);if(0===o.length)return o;var s,u,c,f,h,d,p,v=[],y=o.length;for(s=0;s<y;s++){for(h in p=[],u=o[s][0])u.hasOwnProperty(h)&&(p[h]=u[h]);for(h in n)n.hasOwnProperty(h)&&(p[h]=n[h]);for(f=(i=l(e.slice(1),t.slice(1),p,r)).length,c=0;c<f;c++){for(h in d=i[c][0],u)u.hasOwnProperty(h)&&(d[h]=u[h]);v.push([d,null])}}return v}function c(e,t){var n,r={};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);for(n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);return r}function f(e,t){return this.trunkBindings=t,this.originalCallback=e,this.branches=[],this}function h(e,t){return this.count=0,this.success=!1,this.done=!1,this.callback=e,this.onDone=t,this}f.prototype.checkAllDone=function(){var e;for(e=0;e<this.branches.length;e++)if(!this.branches[e].done)return;i.debug("OPTIONAL BIDNINGS ALL DONE:"),this.doCallBacks(this.branches.length-1,this.trunkBindings)},f.prototype.doCallBacks=function(e,t){var n;if(e<0)return this.originalCallback(t);for(n=0;n<this.branches[e].results.length;n++)this.doCallBacks(e-1,c(t,this.branches[e].results[n]))},h.prototype.reportMatch=function(e){this.callback(e),this.success=!0},h.prototype.reportDone=function(){this.done=!0,i.info("Mandatory query branch finished.***"),void 0!==this.onDone&&this.onDone()};var d=function(e){return this.count=0,this.done=!1,this.results=[],this.junction=e,e.branches.push(this),this};function p(e,t,n){var r,i,o,s,u,l;for(t.nvars=0,t.index=null,r=[t.subject,t.predicate,t.object,t.why],s=[e.subjectIndex,e.predicateIndex,e.objectIndex,e.whyIndex],o=0;o<4;o++){var c=r[o];if(c.uri&&c.uri===a);else if(c.isVar&&void 0===n[c])t.nvars++;else{if(l=void 0,c=void 0===(l=n[u=r[o]])?u:l,e.redirections[c.hashString()]&&(c=e.redirections[c.hashString()]),!(i=s[o][c.hashString()]))return t.index=[],!1;(null===t.index||t.index.length>i.length)&&(t.index=i)}}return null===t.index&&(t.index=e.statements),!0}function v(e,t){return e.nvars!==t.nvars?e.nvars-t.nvars:e.index.length-t.index.length}d.prototype.reportMatch=function(e){this.results.push(e)},d.prototype.reportDone=function(){i.debug("Optional branch finished - results.length = "+this.results.length),0===this.results.length&&(this.results.push({}),i.debug("Optional branch FAILED - that's OK.")),this.done=!0,this.junction.checkAllDone()};var y=function e(n,r,a,u,l,c,h){i.debug("Match begins, Branch count now: "+h.count+" for "+h.pattern_debug);var p,v,y=n.fetcher?n.fetcher:null,g=r.statements;if(0===g.length){if(i.debug("FOUND MATCH WITH BINDINGS:"+s(a)),0===r.optional.length)h.reportMatch(a);else{i.debug("OPTIONAL: "+r.optional);var b,w=new f(t,a),x=[];for(b=0;b<r.optional.length;b++)x[b]=new d(w),x[b].pattern_debug=r.optional[b];for(b=0;b<r.optional.length;b++)x[b].count=x[b].count+1,e(n,r.optional[b],a,"",l,t,x[b])}return h.count--,void i.debug("Match ends -- success , Branch count now: "+h.count+" for "+h.pattern_debug)}var _=g.length;if(y){var k=function(t,i){var o=t.uri.split("#")[0];y.nowOrWhenFetched(o,void 0,function(i,o,s){i||console.log("Error following link to <"+t.uri+"> in query: "+o),e(n,r,a,u,l,c,h)})};for(v=0;v<_;v++){if(p=g[v],void 0!==a[p.subject]&&a[p.subject].uri&&y&&"unrequested"===y.getState(o(a[p.subject].uri)))return void k(a[p.subject]);if(void 0!==a[p.object]&&a[p.object].uri&&y&&"unrequested"===y.getState(o(a[p.object].uri)))return void k(a[p.object])}}m(n,r,a,u,l,c,h)},g=function(e,t){var n,r,i=!0;for(n in e)e.hasOwnProperty(n)&&t[n]&&(r=t[n].test)&&!r(e[n])&&(i=!1);return i},m=function(e,t,n,r,o,a,c){var f,h,d,m,b,w,x,_=t.statements,k=_.length;for(f=0;f<k;f++)p(e,x=_[f],n);_.sort(v),x=_[0];var T,j=e.formula();j.optional=t.optional,j.constraints=t.constraints,j.statements=_.slice(1),i.debug(r+"match2 searching "+x.index.length+" for "+x+"; bindings so far="+s(n));var S,E,O=x.index.length,N=0;for(T=0;T<O;T++)for(E=x.index[T],S=l([x.subject,x.predicate,x.object,x.why],[E.subject,E.predicate,E.object,E.why],n,e),i.info(r+" From first: "+S.length+": "+u(S)),d=S.length,h=0;h<d;h++)if(b=[],w=S[h][0],g(w,t.constraints)){for(m in w)w.hasOwnProperty(m)&&(b[m]=w[m]);for(m in n)n.hasOwnProperty(m)&&(b[m]=n[m]);c.count++,N++,y(e,j,b,r+" ",o,a,c)}else i.debug("Branch count CS: "+c.count);c.count--,0===N&&i.debug("Match2 fails completely on "+x),i.debug("Match2 ends, Branch count: "+c.count+" for "+c.pattern_debug),0===c.count&&(i.debug("Branch finished."),c.reportDone())},b=this;i.debug("Query on "+this.statements.length);var w=new h(t,r);w.count++,e.sync?y(b,e.pat,e.pat.initBindings,"",n,t,w):setTimeout(function(){y(b,e.pat,e.pat.initBindings,"",n,t,w)},0)}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var u=n(6),l=n(10),c=n(1),f=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=o(this,a(t).call(this))).termType=t.termType,n.id=u.nextId++,n.elements=[],n.closed=!1,e&&e.length>0&&e.forEach(function(e){n.elements.push(c.fromValue(e))}),n}var n,r,l;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(t,c),n=t,(r=[{key:"append",value:function(e){return this.elements.push(e)}},{key:"close",value:function(){return this.closed=!0,this.closed}},{key:"shift",value:function(){return this.elements.shift()}},{key:"substitute",value:function(e){return new t(this.elements.map(function(t){t.substitute(e)}))}},{key:"toNT",value:function(){return u.NTAnonymousNodePrefix+this.id}},{key:"toString",value:function(){return"("+this.elements.join(" ")+")"}},{key:"unshift",value:function(e){return this.elements.unshift(e)}}])&&i(n.prototype,r),l&&i(n,l),t}();f.termType="Collection",f.prototype.classOrder=l.Collection,f.prototype.compareTerm=u.prototype.compareTerm,f.prototype.isVar=0,e.exports=f},function(e,t,n){"use strict";(function(t){!t.version||0===t.version.indexOf("v0.")||0===t.version.indexOf("v1.")&&0!==t.version.indexOf("v1.8.")?e.exports={nextTick:function(e,n,r,i){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var o,a,s=arguments.length;switch(s){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick(function(){e.call(null,n)});case 3:return t.nextTick(function(){e.call(null,n,r)});case 4:return t.nextTick(function(){e.call(null,n,r,i)});default:for(o=new Array(s-1),a=0;a<o.length;)o[a++]=arguments[a];return t.nextTick(function(){e.apply(null,o)})}}}:e.exports=t}).call(this,n(4))},function(e,t,n){var r=n(49),i=r.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function a(e,t,n){return i(e,t,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=r:(o(r,t),t.Buffer=a),o(i,a),a.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},a.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";var r=n(6),i=n(18),o=n(78),a=n(32),s=n(16),u=n(11),l=n(0),c=n(22),f=n(23);function h(e){return new l(e)}function d(e,t,n,r){return r=r||new o,new c(e,t,n,r)}e.exports.blankNode=function(e){return new r(e)},e.exports.defaultGraph=function(){return new o},e.exports.graph=function(){return new s},e.exports.literal=function(e,t){return"string"==typeof t?-1===t.indexOf(":")?new u(e,t):new u(e,null,h(t)):new u(e,null,t)},e.exports.namedNode=h,e.exports.quad=d,e.exports.triple=function(e,t,n){return d(e,t,n)},e.exports.variable=function(e){return new f(e)},e.exports.collection=function(e){return new i(e)},e.exports.fetcher=function(e,t){return new a(e,t)},e.exports.lit=function(e,t,n){return new u(""+e,t,n)},e.exports.st=function(e,t,n,r){return new c(e,t,n,r)}},function(e,t,n){"use strict";function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var i=n(1),o=function(){function e(t,n,r,o){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.subject=i.fromValue(t),this.predicate=i.fromValue(n),this.object=i.fromValue(r),this.why=o}var t,n,o;return t=e,(n=[{key:"equals",value:function(e){return e.subject.equals(this.subject)&&e.predicate.equals(this.predicate)&&e.object.equals(this.object)&&e.graph.equals(this.graph)}},{key:"substitute",value:function(t){var n=new e(this.subject.substitute(t),this.predicate.substitute(t),this.object.substitute(t),this.why.substitute(t));return console.log("@@@ statement substitute:"+n),n}},{key:"toCanonical",value:function(){var e=[this.subject.toCanonical(),this.predicate.toCanonical(),this.object.toCanonical()];return this.graph&&"DefaultGraph"!==this.graph.termType&&e.push(this.graph.toCanonical()),e.join(" ")+" ."}},{key:"toNT",value:function(){return[this.subject.toNT(),this.predicate.toNT(),this.object.toNT()].join(" ")+" ."}},{key:"toString",value:function(){return this.toNT()}},{key:"graph",get:function(){return this.why},set:function(e){this.why=e}}])&&r(t.prototype,n),o&&r(t,o),e}();e.exports=o},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var u=n(10),l=n(1),c=n(2),f=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=o(this,a(t).call(this))).termType=t.termType,e.value=n,e.base="varid:",e.uri=c.join(n,e.base),e}var n,r,u;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(t,l),n=t,(r=[{key:"equals",value:function(e){return!!e&&(this.termType===e.termType&&this.value===e.value)}},{key:"hashString",value:function(){return this.toString()}},{key:"substitute",value:function(e){var t;return null!=(t=e[this.toNT()])?t:this}},{key:"toString",value:function(){return this.uri.slice(0,this.base.length)===this.base?"?"+this.uri.slice(this.base.length):"?"+this.uri}}])&&i(n.prototype,r),u&&i(n,u),t}();f.termType="Variable",f.prototype.classOrder=u.Variable,f.prototype.isVar=1,e.exports=f},function(e,t,n){function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var i=n(2),o=n(3).ArrayIndexOf,a=function(){var e=function(e){e=e.replace(/\r\n/g,"\n");for(var t="",n=0;n<e.length;n++){var r=e.charCodeAt(n);r<128?t+=String.fromCharCode(r):r>127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(63&r|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(63&r|128))}return t},t="http://www.w3.org/2000/10/swap/log#",n=function(e){return e},a=function(e){return e},s=function(e){if(e.length>0)throw"missing.js: oops nnonempty dict not imp";return[]},u=function(e){return e.length},l=function(e,t,n){if(void 0===e.slice)throw"@@ mising.js: No .slice function for "+e+" of type "+r(e);return void 0===n||null==n?e.slice(t):e.slice(t,n)},c=Error("dummy error stop iteration"),f=function(e){return this.last=0,this.li=e,this.next=function(){if(this.last==this.li.length)throw c;return this.li[this.last++]},this},h=function(e,t){return e.indexOf(t)},d=function(e,t){if(!e){if(t)throw"python Assertion failed: "+t;throw"(python) Assertion failed."}};String.prototype.encode=function(t){if("utf-8"!=t)throw"UTF8_converter: can only do utf-8";return e(this)},String.prototype.decode=function(e){if("utf-8"!=e)throw"UTF8_converter: can only do utf-8";return this};var p=function(e,t){return i.join(t,e)},v=0;var y="\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~:",g=(new RegExp("^[ \\t]*(#[^\\n]*)?\\r?\\n","g"),new RegExp("^[ \\t]*(#[^\\n]*)?$","g"),new RegExp("^[ \\t]*","g"),new RegExp("^[-+]?[0-9]+","g"),new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?(e[-+]?[0-9]+)?","g")),m=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?"),b=(new RegExp("^[0-9]+","g"),new RegExp('[\\\\\\r\\n\\"]',"g")),w=new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*","g");function x(e,t,n,r,i,o,u,l){void 0===t&&(t=null),void 0===n&&(n=""),void 0===r&&(r=null),void 0===i&&(i=""),void 0===o&&(o=null),void 0===u&&(u=""),void 0===l&&(l=null),this._bindings=new s([]),this._flags=u,""!=n&&(d(n.indexOf(":")>=0,"Document URI not absolute: "+n),this._bindings[""]=n+"#"),this._store=e,i&&e.setGenPrefix(i),this._thisDoc=n,this.source=e.sym(n),this.lines=0,this.statementCount=0,this.startOfLine=0,this.previousLine=0,this._genPrefix=i,this.keywords=new a(["a","this","bind","has","is","of","true","false"]),this.keywordsSet=0,this._anonymousNodes=new s([]),this._variables=new s([]),this._parentVariables=new s([]),this._reason=l,this._reason2=null,v&&(this._reason2=why_BecauseOfData(e.sym(n),this._reason)),this._baseURI=r||(n||null),d(!this._baseURI||this._baseURI.indexOf(":")>=0),this._genPrefix||(this._thisDoc?this._genPrefix=this._thisDoc+"#_g":this._genPrefix=RDFSink_uniqueURI()),null==t?this._thisDoc?this._formula=e.formula(n+"#_formula"):this._formula=e.formula():this._formula=t,this._context=this._formula,this._parentContext=null}function _(e,t,n,r,i){this._str=n.encode("utf-8"),this._str=n,this._i=r,this._why=i,this.lines=t,this._uri=e}function k(e,t,n,r,i){var o=t+1,a="Line "+o+" of <"+e+">: Bad syntax: "+i+'\nat: "'+n.slice(r,r+30)+'"',s=new SyntaxError(a,e,o);return s.lineNo=o,s.characterInFile=r,s.syntaxProblem=i,s}return x.prototype.here=function(e){return this._genPrefix+"_L"+this.lines+"C"+(e-this.startOfLine+1)},x.prototype.formula=function(){return this._formula},x.prototype.loadStream=function(e){return this.loadBuf(e.read())},x.prototype.loadBuf=function(e){return this.startDoc(),this.feed(e),this.endDoc()},x.prototype.feed=function(e){for(var t=e.decode("utf-8"),n=0;n>=0;){var r=this.skipSpace(t,n);if(r<0)return;if((n=this.directiveOrStatement(t,r))<0)throw k(this._thisDoc,this.lines,t,r,"expected directive or statement")}},x.prototype.directiveOrStatement=function(e,t){var n,r=this.skipSpace(e,t);return r<0?r:(n=this.directive(e,r))>=0?this.checkDot(e,n):(n=this.statement(e,r))>=0?this.checkDot(e,n):n},x.prototype.tok=function(e,t,n){if("@"==t.slice(n,n+1))n=n+1;else if(o(this.keywords,e)<0)return-1;var r=n+u(e);return t.slice(n,r)==e&&"\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~".indexOf(t.charAt(r))>=0?r:-1},x.prototype.directive=function(e,t){if((s=this.skipSpace(e,t))<0)return s;var n=new a([]);if((s=this.tok("bind",e,t))>0)throw k(this._thisDoc,this.lines,e,t,"keyword bind is obsolete: use @prefix");if((s=this.tok("keywords",e,t))>0){if((t=this.commaSeparatedList(e,s,n,!1))<0)throw k(this._thisDoc,this.lines,e,t,"'@keywords' needs comma separated list of words");return this.setKeywords(l(n,null,null)),t}if((s=this.tok("forAll",e,t))>0){if((t=this.commaSeparatedList(e,s,n,!0))<0)throw k(this._thisDoc,this.lines,e,t,"Bad variable list after @forAll");var r=new f(n);try{for(;;){var i=r.next();(o(this._variables,i)<0||o(this._parentVariables,i)>=0)&&(this._variables[i]=this._context.newUniversal(i))}}catch(e){if(e!=c)throw e}return t}if((s=this.tok("forSome",e,t))>0){if((t=this.commaSeparatedList(e,s,n,this.uri_ref2))<0)throw k(this._thisDoc,this.lines,e,t,"Bad variable list after @forSome");r=new f(n);try{for(;;){i=r.next();this._context.declareExistential(i)}}catch(e){if(e!=c)throw e}return t}if((s=this.tok("prefix",e,t))>=0){var s,u=new a([]);if((t=this.qname(e,s,u))<0)throw k(this._thisDoc,this.lines,e,s,"expected qname after @prefix");if((s=this.uri_ref2(e,t,u))<0)throw k(this._thisDoc,this.lines,e,t,"expected <uriref> after @prefix _qname_");var h=u[1].uri;if(this._baseURI)h=p(this._baseURI,h);else d(h.indexOf(":")>=0,"With no base URI, cannot handle relative URI for NS");return d(h.indexOf(":")>=0),this._bindings[u[0][0]]=h,this.bind(u[0][0],function(e){return encodeURI(e)}(h)),s}if((s=this.tok("base",e,t))>=0){u=new a([]);if((t=this.uri_ref2(e,s,u))<0)throw k(this._thisDoc,this.lines,e,s,"expected <uri> after @base ");h=u[0].uri;if(!this._baseURI)throw k(this._thisDoc,this.lines,e,s,"With no previous base URI, cannot use relative URI in @base <"+h+">");h=p(this._baseURI,h);return d(h.indexOf(":")>=0),this._baseURI=h,t}return-1},x.prototype.bind=function(e,t){""==e||this._store.setPrefixForURI(e,t)},x.prototype.setKeywords=function(e){null==e?this.keywordsSet=0:(this.keywords=e,this.keywordsSet=1)},x.prototype.startDoc=function(){},x.prototype.endDoc=function(){return this._formula},x.prototype.makeStatement=function(e){e[0].add(e[2],e[1],e[3],this.source),this.statementCount+=1},x.prototype.statement=function(e,t){var n=new a([]);if((t=this.object(e,t,n))<0)return t;var r=this.property_list(e,t,n[0]);if(r<0)throw k(this._thisDoc,this.lines,e,t,"expected propertylist");return r},x.prototype.subject=function(e,t,n){return this.item(e,t,n)},x.prototype.verb=function(e,r,i){if((s=this.skipSpace(e,r))<0)return s;var o=new a([]);if((s=this.tok("has",e,r))>=0){if((r=this.prop(e,s,o))<0)throw k(this._thisDoc,this.lines,e,s,"expected property after 'has'");return i.push(new n(["->",o[0]])),r}if((s=this.tok("is",e,r))>=0){if((r=this.prop(e,s,o))<0)throw k(this._thisDoc,this.lines,e,s,"expected <property> after 'is'");if((s=this.skipSpace(e,r))<0)throw k(this._thisDoc,this.lines,e,r,"End of file found, expected property after 'is'");var s;r=s;if((s=this.tok("of",e,r))<0)throw k(this._thisDoc,this.lines,e,r,"expected 'of' after 'is' <prop>");return i.push(new n(["<-",o[0]])),s}if((s=this.tok("a",e,r))>=0)return i.push(new n(["->",this._store.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")])),s;if("<="==e.slice(r,r+2))return i.push(new n(["<-",this._store.sym(t+"implies")])),r+2;if("="==e.slice(r,r+1))return">"==e.slice(r+1,r+2)?(i.push(new n(["->",this._store.sym(t+"implies")])),r+2):(i.push(new n(["->",this._store.sym("http://www.w3.org/2002/07/owl#sameAs")])),r+1);if(":="==e.slice(r,r+2))return i.push(new n(["->",t+"becomes"])),r+2;if((s=this.prop(e,r,o))>=0)return i.push(new n(["->",o[0]])),s;if(">-"==e.slice(r,r+2)||"<-"==e.slice(r,r+2))throw k(this._thisDoc,this.lines,e,s,">- ... -> syntax is obsolete.");return-1},x.prototype.prop=function(e,t,n){return this.item(e,t,n)},x.prototype.item=function(e,t,n){return this.path(e,t,n)},x.prototype.blankNode=function(e){return this._context.bnode(e,this._reason2)},x.prototype.path=function(e,t,r){if((a=this.nodeOrLiteral(e,t,r))<0)return a;for(;"!^.".indexOf(e.slice(a,a+1))>=0;){var i=e.slice(a,a+1);if("."==i){var o=e.slice(a+1,a+2);if(!o||y.indexOf(o)>=0&&":?<[{(".indexOf(o)<0)break}var a,s=r.pop(),u=this.blankNode(this.here(a));if((a=this.node(e,a+1,r))<0)throw k(this._thisDoc,this.lines,e,a,"EOF found in middle of path syntax");var l=r.pop();"^"==i?this.makeStatement(new n([this._context,l,u,s])):this.makeStatement(new n([this._context,l,s,u])),r.push(u)}return a},x.prototype.anonymousNode=function(e){if(t=this._anonymousNodes[e])return t;var t=this._store.bnode(e);return this._anonymousNodes[e]=t,t},x.prototype.node=function(e,t,r,i){void 0===i&&(i=null);var o=i;if((y=this.skipSpace(e,t))<0)return y;t=y;var l=e.slice(t,t+1);if("["==l){var h=this.here(t);if((y=this.skipSpace(e,t+1))<0)throw k(this._thisDoc,this.lines,e,t,"EOF after '['");if("="==e.slice(y,y+1)){var t=y+1,d=new a([]);if(!((y=this.objectList(e,t,d))>=0))throw k(this._thisDoc,this.lines,e,t,"objectList expected after [= ");o=d[0];if(u(d)>1){var p=new f(d);try{for(;;){var v=p.next();this.makeStatement(new n([this._context,this._store.sym("http://www.w3.org/2002/07/owl#sameAs"),o,v]))}}catch(e){if(e!=c)throw e}}if((y=this.skipSpace(e,y))<0)throw k(this._thisDoc,this.lines,e,t,"EOF when objectList expected after [ = ");if(";"==e.slice(y,y+1))var y=y+1}if(null==o)o=this.blankNode(h);if((t=this.property_list(e,y,o))<0)throw k(this._thisDoc,this.lines,e,y,"property_list expected");if((y=this.skipSpace(e,t))<0)throw k(this._thisDoc,this.lines,e,t,"EOF when ']' expected after [ <propertyList>");if("]"!=e.slice(y,y+1))throw k(this._thisDoc,this.lines,e,y,"']' expected");return r.push(o),y+1}if("{"==l){if("$"==e.slice(t+1,t+2)){for(var y=(t+=1)+1,g=new a([]),m=!0;;){if((t=this.skipSpace(e,y))<0)throw k(this._thisDoc,this.lines,e,t,"needed '$}', found end.");if("$}"==e.slice(t,t+2)){var y=t+2;break}if(m)m=!1;else{if(","!=e.slice(t,t+1))throw k(this._thisDoc,this.lines,e,t,"expected: ','");t+=1}var b=new a([]);if((y=this.item(e,t,b))<0)throw k(this._thisDoc,this.lines,e,t,"expected item in set or '$}'");g.push(b[0])}return r.push(this._store.newSet(g,this._context)),y}var y=t+1,w=this._parentContext;this._parentContext=this._context;var x=this._anonymousNodes,_=this._parentVariables;this._parentVariables=this._variables,this._anonymousNodes=new s([]),this._variables=this._variables.slice();var T=this._reason2;if(this._reason2=null,null==o)o=this._store.formula();for(this._context=o;;){if((t=this.skipSpace(e,y))<0)throw k(this._thisDoc,this.lines,e,t,"needed '}', found end.");if("}"==e.slice(t,t+1)){var y=t+1;break}if((y=this.directiveOrStatement(e,t))<0)throw k(this._thisDoc,this.lines,e,t,"expected statement or '}'")}return this._anonymousNodes=x,this._variables=this._parentVariables,this._parentVariables=_,this._context=this._parentContext,this._reason2=T,this._parentContext=w,r.push(o.close()),y}if("("==l){var j=this._store.list;if("$"==e.slice(t+1,t+2)){j=this._store.newSet;t+=1}for(y=t+1,g=new a([]);;){if((t=this.skipSpace(e,y))<0)throw k(this._thisDoc,this.lines,e,t,"needed ')', found end.");if(")"==e.slice(t,t+1)){y=t+1;break}b=new a([]);if((y=this.item(e,t,b))<0)throw k(this._thisDoc,this.lines,e,t,"expected item in list or ')'");g.push(b[0])}return r.push(j(g,this._context)),y}if((y=this.tok("this",e,t))>=0)throw k(this._thisDoc,this.lines,e,t,"Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords.");if((y=this.tok("true",e,t))>=0)return r.push(!0),y;if((y=this.tok("false",e,t))>=0)return r.push(!1),y;if(null==o&&(y=this.uri_ref2(e,t,r))>=0)return y;return-1},x.prototype.property_list=function(e,t,r){for(;;){if((p=this.skipSpace(e,t))<0)throw k(this._thisDoc,this.lines,e,t,"EOF found when expected verb in property list");if(":-"!=e.slice(p,p+2)){t=p;var i=new a([]);if((p=this.verb(e,t,i))<=0)return t;var o=new a([]);if((t=this.objectList(e,p,o))<0)throw k(this._thisDoc,this.lines,e,p,"objectList expected");var s=new f(o);try{for(;;){var u=s.next(),l=i[0],h=l[0],d=l[1];"->"==h?this.makeStatement(new n([this._context,d,r,u])):this.makeStatement(new n([this._context,d,u,r]))}}catch(e){if(e!=c)throw e}if((p=this.skipSpace(e,t))<0)throw k(this._thisDoc,this.lines,e,p,"EOF found in list of objects");if(";"!=e.slice(t,t+1))return t;t=t+1}else{var p,t=p+2,v=new a([]);if((p=this.node(e,t,v,r))<0)throw k(this._thisDoc,this.lines,e,t,"bad {} or () or [] node after :- ");var t=p}}},x.prototype.commaSeparatedList=function(e,t,n,r){if((i=this.skipSpace(e,t))<0)throw k(this._thisDoc,this.lines,e,i,"EOF found expecting comma sep list");if("."==e.charAt(i))return t;if(r)var i=this.uri_ref2(e,i,n);else i=this.bareWord(e,i,n);if(i<0)return-1;for(;;){if((t=this.skipSpace(e,i))<0)return t;var o=e.slice(t,t+1);if(","!=o)return"."!=o?-1:t;if(r)i=this.uri_ref2(e,t+1,n);else i=this.bareWord(e,t+1,n);if(i<0)throw k(this._thisDoc,this.lines,e,i,"bad list content")}},x.prototype.objectList=function(e,t,n){if((t=this.object(e,t,n))<0)return-1;for(;;){var r=this.skipSpace(e,t);if(r<0)throw k(this._thisDoc,this.lines,e,r,"EOF found after object");if(","!=e.slice(r,r+1))return r;if((t=this.object(e,r+1,n))<0)return t}},x.prototype.checkDot=function(e,t){var n=this.skipSpace(e,t);if(n<0)return n;if("."==e.slice(n,n+1))return n+1;if("}"==e.slice(n,n+1))return n;if("]"==e.slice(n,n+1))return n;throw k(this._thisDoc,this.lines,e,n,"expected '.' or '}' or ']' at end of statement")},x.prototype.uri_ref2=function(e,t,n){var r=new a([]);if((m=this.qname(e,t,r))>=0){var i=r[0],s=i[0],c=i[1];if(null==s){d(0,"not used?");var f=this._baseURI+"#"}else{if(!(f=this._bindings[s])){if("_"==s)return n.push(this.anonymousNode(c)),m;throw k(this._thisDoc,this.lines,e,t,"Prefix "+s+" not bound.")}}var h=this._store.sym(f+c);return o(this._variables,h)>=0?n.push(this._variables[h]):n.push(h),m}if((t=this.skipSpace(e,t))<0)return-1;if("?"==e.charAt(t)){var v=new a([]);return(m=this.variable(e,t,v))>0?(n.push(v[0]),m):-1}if("<"==e.charAt(t)){for(var y=t=t+1;t<u(e);){if(">"==e.charAt(t)){var g=e.slice(y,t);if(this._baseURI)g=p(this._baseURI,g);else d(g.indexOf(":")>=0,"With no base URI, cannot deal with relative URIs");if("#"==e.slice(t-1,t)&&"#"!=l(g,-1,null))g=g+"#";h=this._store.sym(g);return o(this._variables,h)>=0?n.push(this._variables[h]):n.push(h),t+1}t=t+1}throw k(this._thisDoc,this.lines,e,m,"unterminated URI reference")}if(this.keywordsSet){var m;v=new a([]);if((m=this.bareWord(e,t,v))<0)return-1;if(o(this.keywords,v[0])>=0)throw k(this._thisDoc,this.lines,e,t,'Keyword "'+v[0]+'" not allowed here.');return n.push(this._store.sym(this._bindings[""]+v[0])),m}return-1},x.prototype.skipSpace=function(e,t){for(var n=t||0;n<e.length;n++){var r=e.charAt(n);if(" \n\r\t\f\v            ​\u2028\u2029 ".indexOf(r)<0){if("#"!==e.charAt(n))return n;for(;;n++){if(n===e.length)return-1;if("\n"===e.charAt(n)){this.lines=this.lines+1;break}}}else"\n"===e.charAt(n)&&(this.lines=this.lines+1)}return-1},x.prototype.variable=function(e,t,n){if((r=this.skipSpace(e,t))<0)return-1;if("?"!=e.slice(r,r+1))return-1;var r;t=r+=1;if("0123456789-".indexOf(e.charAt(r))>=0)throw k(this._thisDoc,this.lines,e,r,"Varible name can't start with '"+e.charAt(r)+"s'");for(;t<u(e)&&y.indexOf(e.charAt(t))<0;)t=t+1;if(null==this._parentContext)throw k(this._thisDoc,this.lines,e,r,"Can't use ?xxx syntax for variable in outermost level: "+e.slice(r-1,t));return n.push(this._store.variable(e.slice(r,t))),t},x.prototype.bareWord=function(e,t,n){var r=this.skipSpace(e,t);if(r<0)return-1;var i=e.charAt(r);if("0123456789-".indexOf(i)>=0)return-1;if(y.indexOf(i)>=0)return-1;for(t=r;t<u(e)&&y.indexOf(e.charAt(t))<0;)t=t+1;return n.push(e.slice(r,t)),t},x.prototype.qname=function(e,t,r){if((t=this.skipSpace(e,t))<0)return-1;var i=e.charAt(t);if("0123456789-+".indexOf(i)>=0)return-1;if(y.indexOf(i)<0){var a=i;for(t=t+1;t<u(e);){i=e.charAt(t);if(!(y.indexOf(i)<0))break;a=a+i,t=t+1}}else a="";if(t<u(e)&&":"==e.charAt(t)){var s=a;for(t=t+1,a="";t<u(e);){i=e.charAt(t);if(!(y.indexOf(i)<0))break;a=a+i,t=t+1}return r.push(new n([s,a])),t}return a&&this.keywordsSet&&o(this.keywords,a)<0?(r.push(new n(["",a])),t):-1},x.prototype.object=function(e,t,n){if((a=this.subject(e,t,n))>=0)return a;if((a=this.skipSpace(e,t))<0)return-1;t=a;var r=null,i=e.charAt(t);if('"'==i||"'"==i){r=e.slice(t,t+3==i+i)?i+i+i:i;t=t+u(r);var o=this.strconst(e,t,r),a=o[0],s=o[1];return n.push(this._store.literal(s)),a}return-1},x.prototype.nodeOrLiteral=function(e,t,n){if((c=this.node(e,t,n))>=0)return c;if((c=this.skipSpace(e,t))<0)return-1;t=c;var r=e.charAt(t);if("-+0987654321".indexOf(r)>=0){if(m.lastIndex=0,null!=(d=m.exec(e.slice(t)))){c=t+(i=d[0]).length,i.indexOf("T")>=0?n.push(this._store.literal(i,void 0,this._store.sym("http://www.w3.org/2001/XMLSchema#dateTime"))):n.push(this._store.literal(i,void 0,this._store.sym("http://www.w3.org/2001/XMLSchema#date")))}else{var i;if(g.lastIndex=0,null==(d=g.exec(e.slice(t))))throw k(this._thisDoc,this.lines,e,t,"Bad number or date syntax");c=t+g.lastIndex,(i=e.slice(t,c)).indexOf("e")>=0?n.push(this._store.literal(parseFloat(i),void 0,this._store.sym("http://www.w3.org/2001/XMLSchema#double"))):e.slice(t,c).indexOf(".")>=0?n.push(this._store.literal(parseFloat(i),void 0,this._store.sym("http://www.w3.org/2001/XMLSchema#decimal"))):n.push(this._store.literal(parseInt(i),void 0,this._store.sym("http://www.w3.org/2001/XMLSchema#integer")))}return c}if('"'==e.charAt(t)){if('"""'==e.slice(t,t+3))var o='"""';else o='"';t=t+u(o);var s=null,l=this.strconst(e,t,o),c=l[0],f=l[1],h=null;if("@"==e.slice(c,c+1)){var d;if(w.lastIndex=0,null==(d=w.exec(e.slice(c+1))))throw k(this._thisDoc,startline,e,t,"Bad language code syntax on string literal, after @");t=w.lastIndex+c+1,h=e.slice(c+1,t),c=t}if("^^"==e.slice(c,c+2)){var p=new a([]);c=this.uri_ref2(e,c+2,p),s=p[0]}return n.push(this._store.literal(f,h,s)),c}return-1},x.prototype.strconst=function(e,t,r){for(var i=t,o="",a=this.lines;i<u(e);){t=i+u(r);if(e.slice(i,t)==r)return new n([t,o]);if('"'!=e.charAt(i)){if(b.lastIndex=0,!b.exec(e.slice(i)))throw k(this._thisDoc,a,e,i,"Closing quote missing in string at ^ in "+e.slice(i-20,i)+"^"+e.slice(i,i+20));t=i+b.lastIndex-1,o=o+e.slice(i,t);if('"'!=(c=e.charAt(t)))if("\r"!=c){if("\n"==c){if('"'==r)throw k(this._thisDoc,a,e,t,"newline found in string literal");this.lines=this.lines+1;o=o+c,i=t+1;this.previousLine=this.startOfLine,this.startOfLine=i}else if("\\"==c){i=t+1;if(!(c=e.slice(i,i+1)))throw k(this._thisDoc,a,e,t,"unterminated string literal (2)");var s=h('abfrtvn\\"',c);if(s>=0)o=o+'a\b\f\r\t\v\n\\"'.charAt(s),i=i+1;else if("u"==c)i=(l=this.uEscape(e,i+1,a))[0],o=o+(c=l[1]);else{if("U"!=c)throw k(this._thisDoc,this.lines,e,t,"bad escape");var l,c;i=(l=this.UEscape(e,i+1,a))[0],o=o+(c=l[1])}}}else var i=t+1;else var i=t}else var o=o+'"',i=i+1}throw k(this._thisDoc,this.lines,e,t,"unterminated string literal")},x.prototype.uEscape=function(e,t,r){for(var i=t,o=0,a=0;o<4;){var s=e.slice(i,i+1).toLowerCase();i=i+1;if(""==s)throw k(this._thisDoc,r,e,t,"unterminated string literal(3)");var u=h("0123456789abcdef",s);if(u<0)throw k(this._thisDoc,r,e,t,"bad string literal hex escape");a=16*a+u,o=o+1}var l=String.fromCharCode(a);return new n([i,l])},x.prototype.UEscape=function(e,t,r){for(var i=t,o=0,a="\\U";o<8;){var s=e.slice(i,i+1).toLowerCase();i=i+1;if(""==s)throw k(this._thisDoc,r,e,t,"unterminated string literal(3)");if(h("0123456789abcdef",s)<0)throw k(this._thisDoc,r,e,t,"bad string literal hex escape");a=a+s,o=o+1}var u,c=(u="0x"+l(a,2,10)-0,String.fromCharCode(u));return new n([i,c])},_.prototype.toString=function(){var e=this._str,t=this._i,r=0;if(t>60){var i="...";r=t-60}else i="";if(u(e)-t>60)var o="...";else o="";return'Line %i of <%s>: Bad syntax (%s) at ^ in:\n"%s%s^%s%s"'%new n([this.lines+1,this._uri,this._why,i,e.slice(r,t),e.slice(t,t+60),o])},function(e,t,n,r,i,o,a,s){return new x(e,t,n,r,i,o,a,s)}}();e.exports=a},function(e,t,n){(function(t){var n=String.fromCharCode,r="function"==typeof t?t:function(e){setTimeout(e,0)},i=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\[uU]|\\(.)/g,o={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},a=/[\x00-\x20<>\\"\{\}\|\^\`]/;function s(e){if(!(this instanceof s))return new s(e);if(e&&e.lineMode){this._tripleQuotedString=this._number=this._boolean=/$0^/;var t=this;this._tokenize=this.tokenize,this.tokenize=function(e,n){this._tokenize(e,function(e,r){!e&&/^(?:IRI|prefixed|literal|langcode|type|\.|eof)$/.test(r.type)?n&&n(e,r):n&&n(e||t._syntaxError(r.type,n=null))})}}}s.prototype={_iri:/^<((?:[^>\\]|\\[uU])+)>/,_unescapedIri:/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>/,_unescapedString:/^"[^"\\]+"(?=[^"\\])/,_singleQuotedString:/^"[^"\\]*(?:\\.[^"\\]*)*"(?=[^"\\])|^'[^'\\]*(?:\\.[^'\\]*)*'(?=[^'\\])/,_tripleQuotedString:/^""("[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*")""|^''('[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*')''/,_langcode:/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,_prefix:/^((?:[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]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,_prefixed:/^((?:[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]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-: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]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?=\.?[,;\s#()\[\]\{\}"'<])/,_blank:/^_:((?:[0-9A-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]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=\.?[,;:\s#()\[\]\{\}"'<])/,_number:/^[\-+]?(?:\d+\.?\d*([eE](?:[\-\+])?\d+)|\d*\.?\d+)(?=[.,;:\s#()\[\]\{\}"'<])/,_boolean:/^(?:true|false)(?=[.,;:\s#()\[\]\{\}"'<])/,_keyword:/^@[a-z]+(?=[\s#<:])/,_sparqlKeyword:/^(?:PREFIX|BASE|GRAPH)(?=[\s#<:])/i,_shortPredicates:/^a(?=\s+|<)/,_newline:/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,_whitespace:/^[ \t]+/,_endOfFile:/^(?:#[^\n\r]*)?$/,_tokenizeToEnd:function(e,t){for(var n=this._input;;){for(var r;r=this._newline.exec(n);)n=n.substr(r[0].length,n.length),this._line++;if((r=this._whitespace.exec(n))&&(n=n.substr(r[0].length,n.length)),this._endOfFile.test(n))return t&&e(n=null,{line:this._line,type:"eof",value:"",prefix:""}),this._input=n;var i,o=this._line,s="",u="",l="",c=n[0],f=null,h=0,d=!1;switch(c){case"^":if(1===n.length)break;if("^"!==n[1])return p(this);if(this._prevTokenType="^","<"!==(n=n.substr(2))[0]){d=!0;break}case"<":if(f=this._unescapedIri.exec(n))s="IRI",u=f[1];else if(f=this._iri.exec(n)){if(null===(i=this._unescape(f[1]))||a.test(i))return p(this);s="IRI",u=i}break;case"_":((f=this._blank.exec(n))||t&&(f=this._blank.exec(n+" ")))&&(s="prefixed",l="_",u=f[1]);break;case'"':case"'":if(f=this._unescapedString.exec(n))s="literal",u=f[0];else if(f=this._singleQuotedString.exec(n)){if(null===(i=this._unescape(f[0])))return p(this);s="literal",u=i.replace(/^'|'$/g,'"')}else if(f=this._tripleQuotedString.exec(n)){if(i=f[1]||f[2],this._line+=i.split(/\r\n|\r|\n/).length-1,null===(i=this._unescape(i)))return p(this);s="literal",u=i.replace(/^'|'$/g,'"')}break;case"@":"literal"===this._prevTokenType&&(f=this._langcode.exec(n))?(s="langcode",u=f[1]):(f=this._keyword.exec(n))&&(s=f[0]);break;case".":if(1===n.length?t:n[1]<"0"||n[1]>"9"){s=".",h=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(f=this._number.exec(n))&&(s="literal",u='"'+f[0]+'"^^http://www.w3.org/2001/XMLSchema#'+(f[1]?"double":/^[+\-]?\d+$/.test(f[0])?"integer":"decimal"));break;case"B":case"b":case"p":case"P":case"G":case"g":(f=this._sparqlKeyword.exec(n))?s=f[0].toUpperCase():d=!0;break;case"f":case"t":(f=this._boolean.exec(n))?(s="literal",u='"'+f[0]+'"^^http://www.w3.org/2001/XMLSchema#boolean'):d=!0;break;case"a":(f=this._shortPredicates.exec(n))?(s="abbreviation",u="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):d=!0;break;case",":case";":case"[":case"]":case"(":case")":case"{":case"}":h=1,s=c;break;default:d=!0}if(d&&("@prefix"!==this._prevTokenType&&"PREFIX"!==this._prevTokenType||!(f=this._prefix.exec(n))?((f=this._prefixed.exec(n))||t&&(f=this._prefixed.exec(n+" ")))&&(s="prefixed",l=f[1]||"",u=this._unescape(f[2])):(s="prefix",u=f[1]||"")),"^"===this._prevTokenType&&(s="IRI"===s||"prefixed"===s?"type":""),!s)return t||!/^'''|^"""/.test(n)&&/\n|\r/.test(n)?p(this):this._input=n;e(null,{line:o,type:s,value:u,prefix:l}),this._prevTokenType=s,n=n.substr(h||f[0].length,n.length)}function p(t){e(t._syntaxError(/^\S*/.exec(n)[0]))}},_unescape:function(e){try{return e.replace(i,function(e,t,r,i){var a;if(t){if(a=parseInt(t,16),isNaN(a))throw new Error;return n(a)}if(r){if(a=parseInt(r,16),isNaN(a))throw new Error;return a<=65535?n(a):n(55296+(a-=65536)/1024,56320+(1023&a))}var s=o[i];if(!s)throw new Error;return s})}catch(e){return null}},_syntaxError:function(e){return this._input=null,new Error('Syntax error: unexpected "'+e+'" on line '+this._line+".")},tokenize:function(e,t){var n=this;function i(e){null!==n._input&&(n._input+=e,n._tokenizeToEnd(t,!1))}function o(){null!==n._input&&n._tokenizeToEnd(t,!0)}this._line=1,"string"==typeof e?(this._input=e,r(function(){n._tokenizeToEnd(t,!0)})):(this._input="",e&&"function"!=typeof e?("function"==typeof e.setEncoding&&e.setEncoding("utf8"),e.on("data",i),e.on("end",o)):(this.addChunk=i,this.end=o,t||(t=e)))}},e.exports=s}).call(this,n(14).setImmediate)},function(e,t,n){var r=n(25),i="http://www.w3.org/1999/02/22-rdf-syntax-ns#",o=i+"nil",a=i+"first",s=/^[a-z][a-z0-9+.-]*:/i,u=/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i,l=/(?:^|\/)\.\.?(?:$|[\/#?])/,c=0,f=0;function h(e){if(!(this instanceof h))return new h(e);this._tripleStack=[],this._graph=null,e=e||{},this._setBase(e.documentIRI);var t="string"==typeof e.format&&e.format.match(/\w*$/)[0].toLowerCase(),n="turtle"===t,i="trig"===t,o=/triple/.test(t),a=/quad/.test(t),s=o||a;(this._supportsNamedGraphs=!n)||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(n||i||o),s&&(this._base="",this._resolveIRI=function(e){return this._error("Disallowed relative IRI",e),this._callback=d,this._subject=null}),this._blankNodePrefix="string"!=typeof e.blankNodePrefix?"":"_:"+e.blankNodePrefix.replace(/^_:/,""),this._lexer=e.lexer||new r({lineMode:s})}function d(){}h._resetBlankNodeIds=function(){c=f=0},h.prototype={_setBase:function(e){if(e){if(e.indexOf("#")>=0)throw new Error("Invalid base IRI "+e)}else e=null;(this._base=e)&&(this._basePath=e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(u),this._baseRoot=e[0],this._baseScheme=e[1])},_readInTopContext:function(e){switch(e.type){case"eof":return null!==this._graph?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"@prefix":return this._sparqlStyle=!1,this._readPrefix;case"PREFIX":return this._sparqlStyle=!0,this._readPrefix;case"@base":return this._sparqlStyle=!1,this._readBaseIRI;case"BASE":return this._sparqlStyle=!0,this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}},_readSubject:function(e){switch(this._predicate=null,e.type){case"IRI":null===this._base||s.test(e.value)?this._subject=e.value:this._subject=this._resolveIRI(e);break;case"prefixed":var t=this._prefixes[e.prefix];if(void 0===t)return this._error('Undefined prefix "'+e.prefix+':"',e);this._subject=t+e.value;break;case"[":return this._subject="_:b"+f++,this._tripleStack.push({subject:this._subject,predicate:null,object:null,type:"blank"}),this._readBlankNodeHead;case"(":return this._tripleStack.push({subject:o,predicate:null,object:null,type:"list"}),this._subject=null,this._readListItem;case"}":return this._readPunctuation(e);default:return this._error("Expected subject but got "+e.type,e)}return this._readPredicateOrNamedGraph},_readPredicate:function(e){var t=e.type;switch(t){case"IRI":case"abbreviation":null===this._base||s.test(e.value)?this._predicate=e.value:this._predicate=this._resolveIRI(e);break;case"prefixed":if("_"===e.prefix)return this._error("Disallowed blank node as predicate",e);var n=this._prefixes[e.prefix];if(void 0===n)return this._error('Undefined prefix "'+e.prefix+':"',e);this._predicate=n+e.value;break;case".":case"]":case"}":return null===this._predicate?this._error("Unexpected "+t,e):(this._subject=null,"]"===t?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._readPredicate;default:return this._error('Expected predicate to follow "'+this._subject+'"',e)}return this._readObject},_readObject:function(e){switch(e.type){case"IRI":null===this._base||s.test(e.value)?this._object=e.value:this._object=this._resolveIRI(e);break;case"prefixed":var t=this._prefixes[e.prefix];if(void 0===t)return this._error('Undefined prefix "'+e.prefix+':"',e);this._object=t+e.value;break;case"literal":return this._object=e.value,this._readDataTypeOrLang;case"[":var n="_:b"+f++;return this._tripleStack.push({subject:this._subject,predicate:this._predicate,object:n,type:"blank"}),this._subject=n,this._readBlankNodeHead;case"(":return this._tripleStack.push({subject:this._subject,predicate:this._predicate,object:o,type:"list"}),this._subject=null,this._readListItem;default:return this._error('Expected object to follow "'+this._predicate+'"',e)}return this._getTripleEndReader()},_readPredicateOrNamedGraph:function(e){return"{"===e.type?this._readGraph(e):this._readPredicate(e)},_readGraph:function(e){return"{"!==e.type?this._error("Expected graph but got "+e.type,e):(this._graph=this._subject,this._subject=null,this._readSubject)},_readBlankNodeHead:function(e){return"]"===e.type?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))},_readBlankNodeTail:function(e){if("]"!==e.type)return this._readBlankNodePunctuation(e);null!==this._subject&&this._callback(null,{subject:this._subject,predicate:this._predicate,object:this._object,graph:this._graph||""});var t=this._tripleStack.pop();return this._subject=t.subject,null!==t.object?(this._predicate=t.predicate,this._object=t.object,this._getTripleEndReader()):null!==this._predicate?this._readPredicate:this._readPredicateOrNamedGraph},_readDataTypeOrLang:function(e){switch(e.type){case"type":var t;if(""===e.prefix)t=null===this._base||s.test(e.value)?e.value:this._resolveIRI(e);else{var n=this._prefixes[e.prefix];if(void 0===n)return this._error('Undefined prefix "'+e.prefix+':"',e);t=n+e.value}return this._object+="^^"+t,this._getTripleEndReader();case"langcode":return this._object+="@"+e.value.toLowerCase(),this._getTripleEndReader();default:return this._getTripleEndReader().call(this,e)}},_readListItem:function(e){var t=null,n=null,r=this._subject,i=this._tripleStack,u=i[i.length-1],l=this._readListItem;switch(e.type){case"IRI":t=null===this._base||s.test(e.value)?e.value:this._resolveIRI(e);break;case"prefixed":var c=this._prefixes[e.prefix];if(void 0===c)return this._error('Undefined prefix "'+e.prefix+':"',e);t=c+e.value;break;case"literal":t=e.value,l=this._readDataTypeOrLang;break;case"[":n="_:b"+f++,t="_:b"+f++,i.push({subject:n,predicate:a,object:t,type:"blank"}),this._subject=t,l=this._readBlankNodeHead;break;case"(":n="_:b"+f++,i.push({subject:n,predicate:a,object:o,type:"list"}),this._subject=null,l=this._readListItem;break;case")":if(i.pop(),0!==i.length&&"list"===i[i.length-1].type&&this._callback(null,{subject:u.subject,predicate:u.predicate,object:u.object,graph:this._graph||""}),this._subject=u.subject,null===u.predicate){if(l=this._readPredicate,u.subject===o)return l}else if(this._predicate=u.predicate,this._object=u.object,l=this._getTripleEndReader(),u.object===o)return l;n=o;break;default:return this._error('Expected list item instead of "'+e.type+'"',e)}return null===n&&(this._subject=n="_:b"+f++),null===r?u.object===o?u.object=n:u.subject=n:this._callback(null,{subject:r,predicate:"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest",object:n,graph:this._graph||""}),null!==t&&this._callback(null,{subject:n,predicate:a,object:t,graph:this._graph||""}),l},_readPunctuation:function(e){var t,n=this._subject,r=this._graph;switch(e.type){case"}":if(null===this._graph)return this._error("Unexpected graph closing",e);this._graph=null;case".":this._subject=null,t=this._readInTopContext;break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"IRI":if(this._supportsQuads&&null===this._graph){r=null===this._base||s.test(e.value)?e.value:this._resolveIRI(e),n=this._subject,t=this._readQuadPunctuation;break}case"prefixed":if(this._supportsQuads&&null===this._graph){var i=this._prefixes[e.prefix];if(void 0===i)return this._error('Undefined prefix "'+e.prefix+':"',e);r=i+e.value,t=this._readQuadPunctuation;break}default:return this._error('Expected punctuation to follow "'+this._object+'"',e)}return null!==n&&this._callback(null,{subject:n,predicate:this._predicate,object:this._object,graph:r||""}),t},_readBlankNodePunctuation:function(e){var t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error('Expected punctuation to follow "'+this._object+'"',e)}return this._callback(null,{subject:this._subject,predicate:this._predicate,object:this._object,graph:this._graph||""}),t},_readQuadPunctuation:function(e){return"."!==e.type?this._error("Expected dot to follow quad",e):this._readInTopContext},_readPrefix:function(e){return"prefix"!==e.type?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)},_readPrefixIRI:function(e){return"IRI"!==e.type?this._error('Expected IRI to follow prefix "'+this._prefix+':"',e):(t=null===this._base||s.test(e.value)?e.value:this._resolveIRI(e),this._prefixes[this._prefix]=t,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation);var t},_readBaseIRI:function(e){if("IRI"!==e.type)return this._error("Expected IRI to follow base declaration",e);try{this._setBase(null===this._base||s.test(e.value)?e.value:this._resolveIRI(e))}catch(t){this._error(t.message,e)}return this._readDeclarationPunctuation},_readNamedGraphLabel:function(e){switch(e.type){case"IRI":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}},_readNamedGraphBlankLabel:function(e){return"]"!==e.type?this._error("Invalid graph label",e):(this._subject="_:b"+f++,this._readGraph)},_readDeclarationPunctuation:function(e){return this._sparqlStyle?this._readInTopContext(e):"."!==e.type?this._error("Expected declaration to end with a dot",e):this._readInTopContext},_getTripleEndReader:function(){var e=this._tripleStack;if(0===e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem}},_error:function(e,t){this._callback(new Error(e+" at line "+t.line+"."))},_resolveIRI:function(e){var t=e.value;switch(t[0]){case void 0:return this._base;case"#":return this._base+t;case"?":return this._base.replace(/(?:\?.*)?$/,t);case"/":return("/"===t[1]?this._baseScheme:this._baseRoot)+this._removeDotSegments(t);default:return this._removeDotSegments(this._basePath+t)}},_removeDotSegments:function(e){if(!l.test(e))return e;for(var t="",n=e.length,r=-1,i=-1,o=0,a="/";r<n;){switch(a){case":":if(i<0&&"/"===e[++r]&&"/"===e[++r])for(;(i=r+1)<n&&"/"!==e[i];)r=i;break;case"?":case"#":r=n;break;case"/":if("."===e[r+1])switch(a=e[++r+1]){case"/":t+=e.substring(o,r-1),o=r+1;break;case void 0:case"?":case"#":return t+e.substring(o,r)+e.substr(r+1);case".":if(void 0===(a=e[++r+1])||"/"===a||"?"===a||"#"===a){if((o=(t+=e.substring(o,r-2)).lastIndexOf("/"))>=i&&(t=t.substr(0,o)),"/"!==a)return t+"/"+e.substr(r+1);o=r+1}}}a=e[++r]}return t+e.substring(o)},parse:function(e,t,n){this._readCallback=this._readInTopContext,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix||"_:b"+c+++"_","function"==typeof e&&(n=t,t=e,e=null),this._callback=t||d,this._prefixCallback=n||d;var r=this;this._lexer.tokenize(e,function(e,t){null!==e?(r._callback(e),r._callback=d):void 0!==r._readCallback&&(r._readCallback=r._readCallback(t))}),e||(this.addChunk=this._lexer.addChunk,this.end=this._lexer.end)}},e.exports=h},function(e,t){var n={isIRI:function(e){if(!e)return e;var t=e[0];return'"'!==t&&"_"!==t},isLiteral:function(e){return e&&'"'===e[0]},isBlank:function(e){return e&&"_:"===e.substr(0,2)},getLiteralValue:function(e){var t=/^"([^]*)"/.exec(e);if(!t)throw new Error(e+" is not a literal");return t[1]},getLiteralType:function(e){var t=/^"[^]*"(?:\^\^([^"]+)|(@)[^@"]+)?$/.exec(e);if(!t)throw new Error(e+" is not a literal");return t[1]||(t[2]?"http://www.w3.org/1999/02/22-rdf-syntax-ns#langString":"http://www.w3.org/2001/XMLSchema#string")},getLiteralLanguage:function(e){var t=/^"[^]*"(?:@([^@"]+)|\^\^[^"]+)?$/.exec(e);if(!t)throw new Error(e+" is not a literal");return t[1]?t[1].toLowerCase():""},isPrefixedName:function(e){return e&&/^[^:\/"']*:[^:\/"']+$/.test(e)},expandPrefixedName:function(e,t){var n,r,i,o=/(?:^|"\^\^)([^:\/#"'\^_]*):[^\/]*$/.exec(e);return o&&(r=t[n=o[1]],i=o.index),void 0===r?e:0===i?r+e.substr(n.length+1):e.substr(0,i+3)+r+e.substr(i+n.length+4)},createIRI:function(e){return e&&'"'===e[0]?n.getLiteralValue(e):e},createLiteral:function(e,t){if(!t)switch(typeof e){case"boolean":t="http://www.w3.org/2001/XMLSchema#boolean";break;case"number":if(isFinite(e)){t=e%1==0?"http://www.w3.org/2001/XMLSchema#integer":"http://www.w3.org/2001/XMLSchema#decimal";break}default:return'"'+e+'"'}return'"'+e+(/^[a-z]+(-[a-z0-9]+)*$/i.test(t)?'"@'+t.toLowerCase():'"^^'+t)}};function r(e,t){for(var r in n)t?e.prototype[r]=i(n[r]):e[r]=n[r];return e}function i(e){return function(t){return e(this,t)}}e.exports=r(r)},function(e,t,n){"use strict";var r,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var u=10;function l(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,a,s;if("function"!=typeof n)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n);if(void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),a=o[t]),void 0===a)a=o[t]=n,++e._eventsCount;else if("function"==typeof a?a=o[t]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),(i=l(e))>0&&a.length>i&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,console&&console.warn&&console.warn(s)}return e}function f(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=function(){for(var e=[],t=0;t<arguments.length;t++)e.push(arguments[t]);this.fired||(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,o(this.listener,this.target,e))}.bind(r);return i.listener=n,r.wrapFn=i,i}function h(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):p(i,i.length)}function d(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return u},set:function(e){if("number"!=typeof e||e<0||a(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");u=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||a(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var l=u.length,c=p(u,l);for(n=0;n<l;++n)o(c[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t);return this.on(e,f(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t);return this.prependListener(e,f(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,o,a;if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t);if(void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return h(this,e,!0)},s.prototype.rawListeners=function(e){return h(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},function(e,t,n){(t=e.exports=n(46)).Stream=t,t.Readable=t,t.Writable=n(30),t.Duplex=n(8),t.Transform=n(52),t.PassThrough=n(72)},function(e,t,n){"use strict";(function(t,r,i){var o=n(19);function a(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;e.entry=null;for(;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}(t,e)}}e.exports=m;var s,u=!t.browser&&["v0.10","v0.9."].indexOf(t.version.slice(0,5))>-1?r:o.nextTick;m.WritableState=g;var l=n(15);l.inherits=n(7);var c={deprecate:n(71)},f=n(48),h=n(20).Buffer,d=i.Uint8Array||function(){};var p,v=n(50);function y(){}function g(e,t){s=s||n(8),e=e||{};var r=t instanceof s;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var i=e.highWaterMark,l=e.writableHighWaterMark,c=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(l||0===l)?l:c,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var f=!1===e.decodeStrings;this.decodeStrings=!f,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,i){--t.pendingcb,n?(o.nextTick(i,r),o.nextTick(T,e,t),e._writableState.errorEmitted=!0,e.emit("error",r)):(i(r),e._writableState.errorEmitted=!0,e.emit("error",r),T(e,t))}(e,n,r,t,i);else{var a=_(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||x(e,n),r?u(w,e,n,a,i):w(e,n,a,i)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function m(e){if(s=s||n(8),!(p.call(m,this)||this instanceof s))return new m(e);this._writableState=new g(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),f.call(this)}function b(e,t,n,r,i,o,a){t.writelen=r,t.writecb=a,t.writing=!0,t.sync=!0,n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function w(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),T(e,t)}function x(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,i=new Array(r),o=t.corkedRequestsFree;o.entry=n;for(var s=0,u=!0;n;)i[s]=n,n.isBuf||(u=!1),n=n.next,s+=1;i.allBuffers=u,b(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,c=n.encoding,f=n.callback;if(b(e,t,!1,t.objectMode?1:l.length,l,c,f),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function _(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function k(e,t){e._final(function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),T(e,t)})}function T(e,t){var n=_(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,o.nextTick(k,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}l.inherits(m,f),g.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(g.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===m&&(e&&e._writableState instanceof g)}})):p=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,n){var r,i=this._writableState,a=!1,s=!i.objectMode&&(r=e,h.isBuffer(r)||r instanceof d);return s&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=y),i.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),o.nextTick(t,n)}(this,n):(s||function(e,t,n,r){var i=!0,a=!1;return null===n?a=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),o.nextTick(r,a),i=!1),i}(this,i,e,n))&&(i.pendingcb++,a=function(e,t,n,r,i,o){if(!n){var a=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,n));return t}(t,r,i);r!==a&&(n=!0,i="buffer",r=a)}var s=t.objectMode?1:r.length;t.length+=s;var u=t.length<t.highWaterMark;u||(t.needDrain=!0);if(t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else b(e,t,!1,s,r,i,o);return u}(this,i,s,e,t,n)),a},m.prototype.cork=function(){this._writableState.corked++},m.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||x(this,e))},m.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(m.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),m.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||function(e,t,n){t.ending=!0,T(e,t),n&&(t.finished?o.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=v.destroy,m.prototype._undestroy=v.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,n(4),n(14).setImmediate,n(5))},function(e,t){var n=/^"([^]*)"(?:\^\^(.+)|@([\-a-z]+))?$/i,r=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,i=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,o={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};function a(e,t){if(!(this instanceof a))return new a(e,t);if(e&&"function"!=typeof e.write&&(t=e,e=null),t=t||{},e)this._outputStream=e,this._endStream=void 0===t.end||!!t.end;else{var n="";this._outputStream={write:function(e,t,r){n+=e,r&&r()},end:function(e){e&&e(null,n)}},this._endStream=!0}this._subject=null,/triple|quad/i.test(t.format)?this._writeTriple=this._writeTripleLine:(this._graph="",this._prefixIRIs=Object.create(null),t.prefixes&&this.addPrefixes(t.prefixes))}function s(e){var t=o[e];return void 0===t&&(1===e.length?(t=e.charCodeAt(0).toString(16),t="\\u0000".substr(0,6-t.length)+t):(t=(1024*(e.charCodeAt(0)-55296)+e.charCodeAt(1)+9216).toString(16),t="\\U00000000".substr(0,10-t.length)+t)),t}a.prototype={_write:function(e,t){this._outputStream.write(e,"utf8",t)},_writeTriple:function(e,t,n,r,i){try{this._graph!==r&&(this._write((null===this._subject?"":this._graph?"\n}\n":".\n")+(r?this._encodeIriOrBlankNode(r)+" {\n":"")),this._subject=null,this._graph="["!==r[0]?r:"]"),this._subject===e?this._predicate===t?this._write(", "+this._encodeObject(n),i):this._write(";\n "+this._encodePredicate(this._predicate=t)+" "+this._encodeObject(n),i):this._write((null===this._subject?"":".\n")+this._encodeSubject(this._subject=e)+" "+this._encodePredicate(this._predicate=t)+" "+this._encodeObject(n),i)}catch(e){i&&i(e)}},_writeTripleLine:function(e,t,n,r,i){delete this._prefixMatch;try{this._write(this._encodeIriOrBlankNode(e)+" "+this._encodeIriOrBlankNode(t)+" "+this._encodeObject(n)+(r?" "+this._encodeIriOrBlankNode(r)+".\n":".\n"),i)}catch(e){i&&i(e)}},_encodeIriOrBlankNode:function(e){var t=e[0];if("["===t||"("===t||"_"===t&&":"===e[1])return e;r.test(e)&&(e=e.replace(i,s));var n=this._prefixRegex.exec(e);return n?n[1]?this._prefixIRIs[n[1]]+n[2]:e:"<"+e+">"},_encodeLiteral:function(e,t,n){return r.test(e)&&(e=e.replace(i,s)),n?'"'+e+'"@'+n:t?'"'+e+'"^^'+this._encodeIriOrBlankNode(t):'"'+e+'"'},_encodeSubject:function(e){if('"'===e[0])throw new Error("A literal as subject is not allowed: "+e);return"["===e[0]&&(this._subject="]"),this._encodeIriOrBlankNode(e)},_encodePredicate:function(e){if('"'===e[0])throw new Error("A literal as predicate is not allowed: "+e);return"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"===e?"a":this._encodeIriOrBlankNode(e)},_encodeObject:function(e){if('"'!==e[0])return this._encodeIriOrBlankNode(e);var t=n.exec(e);if(!t)throw new Error("Invalid literal: "+e);return this._encodeLiteral(t[1],t[2],t[3])},_blockedWrite:function(){throw new Error("Cannot write because the writer has been closed.")},addTriple:function(e,t,n,r,i){void 0===n?this._writeTriple(e.subject,e.predicate,e.object,e.graph||"",t):"string"!=typeof r?this._writeTriple(e,t,n,"",r):this._writeTriple(e,t,n,r,i)},addTriples:function(e){for(var t=0;t<e.length;t++)this.addTriple(e[t])},addPrefix:function(e,t,n){var r={};r[e]=t,this.addPrefixes(r,n)},addPrefixes:function(e,t){var n=this._prefixIRIs,r=!1;for(var i in e){var o=e[i];/[#\/]$/.test(o)&&n[o]!==(i+=":")&&(r=!0,n[o]=i,null!==this._subject&&(this._write(this._graph?"\n}\n":".\n"),this._subject=null,this._graph=""),this._write("@prefix "+i+" <"+o+">.\n"))}if(r){var a="",s="";for(var u in n)a+=a?"|"+u:u,s+=(s?"|":"")+n[u];a=a.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&"),this._prefixRegex=new RegExp("^(?:"+s+")[^/]*$|^("+a+")([a-zA-Z][\\-_a-zA-Z0-9]*)$")}this._write(r?"\n":"",t)},blank:function(e,t){var n,r,i=e;switch(void 0===e?i=[]:"string"==typeof e?i=[{predicate:e,object:t}]:"length"in e||(i=[e]),r=i.length){case 0:return"[]";case 1:if("["!==(n=i[0]).object[0])return"[ "+this._encodePredicate(n.predicate)+" "+this._encodeObject(n.object)+" ]";default:for(var o="[",a=0;a<r;a++)(n=i[a]).predicate===e?o+=", "+this._encodeObject(n.object):(o+=(a?";\n ":"\n ")+this._encodePredicate(n.predicate)+" "+this._encodeObject(n.object),e=n.predicate);return o+"\n]"}},list:function(e){for(var t=e&&e.length||0,n=new Array(t),r=0;r<t;r++)n[r]=this._encodeObject(e[r]);return"("+n.join(" ")+")"},_prefixRegex:/$0^/,end:function(e){null!==this._subject&&(this._write(this._graph?"\n}\n":".\n"),this._subject=null),this._write=this._blockedWrite;var t=e&&function(n,r){t=null,e(n,r)};if(this._endStream)try{return this._outputStream.end(t)}catch(e){}t&&t()}},e.exports=a},function(e,t,n){function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}function a(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function s(e){return(s=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&l(e,t)}function l(e,t){return(l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var f=n(16),h=n(9),d=n(24),p=n(0),v=n(12),y=n(56),g=n(35).parseRDFaDOM,m=n(36),b=n(2),w=n(3),x=n(33),_=("undefined"==typeof window?n(80):n(81)).fetch,k={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/ld+json":!0},T={rdf:"application/rdf+xml",owl:"application/rdf+xml",n3:"text/n3",ttl:"text/turtle",nt:"text/n3",acl:"text/n3",html:"text/html",xml:"text/xml"},j={link:v("http://www.w3.org/2007/ont/link#"),http:v("http://www.w3.org/2007/ont/http#"),httph:v("http://www.w3.org/2007/ont/httph#"),rdf:v("http://www.w3.org/1999/02/22-rdf-syntax-ns#"),rdfs:v("http://www.w3.org/2000/01/rdf-schema#"),dc:v("http://purl.org/dc/elements/1.1/"),ldp:v("http://www.w3.org/ns/ldp#")},S=function e(t,n){c(this,e),this.response=t,this.dom=n},E=function(e){function t(){return c(this,t),a(this,s(t).apply(this,arguments))}return u(t,S),o(t,[{key:"parse",value:function(e,t,n,r){var i=e.store;if(this.dom||(this.dom=w.parseXML(t)),"parsererror"===this.dom.documentElement.nodeName)return e.failFetch(n,"Badly formed XML in "+n.resource.uri,"parse_error");var o=new m(i);try{o.parse(this.dom,n.original.uri,n.original,r)}catch(t){return e.failFetch(n,"Syntax error parsing RDF/XML! "+t,"parse_error")}return n.noMeta||i.add(n.original,j.rdf("type"),j.link("RDFDocument"),e.appNode),e.doneFetch(n,this.response)}}],[{key:"toString",value:function(){return"RDFXMLHandler"}},{key:"register",value:function(e){e.mediatypes["application/rdf+xml"]={q:.9}}}]),t}();E.pattern=new RegExp("application/rdf\\+xml");var O=function(e){function t(){return c(this,t),a(this,s(t).apply(this,arguments))}return u(t,S),o(t,[{key:"parse",value:function(e,t,n,r){var i,o;this.dom||(this.dom=w.parseXML(t));var a=e.store,s=this.dom.getElementsByTagName("title");s.length>0&&a.add(n.resource,j.dc("title"),a.literal(s[0].textContent),n.resource);for(var u=this.dom.getElementsByTagName("link"),l=u.length-1;l>=0;l--)o=!1,(i=u[l].getAttribute("rel"))||(i=u[l].getAttribute("rev"),o=!0),i&&e.linkData(n.original,i,u[l].getAttribute("href"),n.resource,o);for(var c=this.dom.getElementsByTagName("script"),f=0;f<c.length;f++){var h=c[f].getAttribute("type");k[h]&&(y(c[f].textContent,a,n.original.uri,h),y(c[f].textContent,a,n.original.uri,h))}if(n.noMeta||a.add(n.resource,j.rdf("type"),j.link("WebPage"),e.appNode),!n.noRDFa&&g)try{g(this.dom,a,n.original.uri)}catch(t){var d="Error trying to parse "+n.resource+" as RDFa:\n"+t+":\n"+t.stack;return e.failFetch(n,d,"parse_error")}return e.doneFetch(n,this.response)}}],[{key:"toString",value:function(){return"XHTMLHandler"}},{key:"register",value:function(e){e.mediatypes["application/xhtml+xml"]={}}}]),t}();O.pattern=new RegExp("application/xhtml");var N=function(e){function t(){return c(this,t),a(this,s(t).apply(this,arguments))}return u(t,S),o(t,[{key:"parse",value:function(e,t,n,r){for(var i=w.parseXML(t),o=0;o<i.childNodes.length;o++)if(1===i.childNodes[o].nodeType){var a=i.childNodes[o].namespaceURI;if(a&&a===a.rdf)return e.addStatus(n.req,"Has XML root element in the RDF namespace, so assume RDF/XML."),new E(this.response,i).parse(e,t,n,r);break}if(i.doctype&&("html"===i.doctype.name&&i.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/)&&i.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)))return e.addStatus(n.req,"Has XHTML DOCTYPE. Switching to XHTML Handler.\n"),new O(this.response,i).parse(e,t,n,r);var s=i.getElementsByTagName("html")[0];if(s){var u=s.getAttribute("xmlns");if(u&&u.match(/^http:\/\/www.w3.org\/1999\/xhtml/))return e.addStatus(n.req,"Has a default namespace for XHTML. Switching to XHTMLHandler.\n"),new O(this.response,i).parse(e,t,n,r)}return e.failFetch(n,"Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n"+t.slice(0,80),901)}}],[{key:"toString",value:function(){return"XMLHandler"}},{key:"register",value:function(e){e.mediatypes["text/xml"]={q:.5},e.mediatypes["application/xml"]={q:.5}}}]),t}();N.pattern=new RegExp("(text|application)/(.*)xml");var I=function(e){function t(){return c(this,t),a(this,s(t).apply(this,arguments))}return u(t,S),o(t,[{key:"parse",value:function(e,t,n,r){var i=e.store;if(t.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/))return e.addStatus(n.req,"Has an XML declaration. We'll assume it's XHTML as the content-type was text/html.\n"),new O(this.response).parse(e,t,n,r);if(t.match(/.*<!DOCTYPE\s+html[^<]+-\/\/W3C\/\/DTD XHTML[^<]+http:\/\/www.w3.org\/TR\/xhtml[^<]+>/))return e.addStatus(n.req,"Has XHTML DOCTYPE. Switching to XHTMLHandler.\n"),new O(this.response).parse(e,t,n,r);if(t.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/))return e.addStatus(n.req,"Has default namespace for XHTML, so switching to XHTMLHandler.\n"),new O(this.response).parse(e,t,n,r);var o=new RegExp("<title>([\\s\\S]+?)","im").exec(t);return o&&i.add(n.resource,j.dc("title"),i.literal(o[1]),n.resource),i.add(n.resource,j.rdf("type"),j.link("WebPage"),e.appNode),e.addStatus(n.req,"non-XML HTML document, not parsed for data."),e.doneFetch(n,this.response)}}],[{key:"toString",value:function(){return"HTMLHandler"}},{key:"register",value:function(e){e.mediatypes["text/html"]={q:.9}}}]),t}();I.pattern=new RegExp("text/html");var R=function(e){function t(){return c(this,t),a(this,s(t).apply(this,arguments))}return u(t,S),o(t,[{key:"parse",value:function(e,t,n,r){return t.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)?(e.addStatus(n.req,"Warning: "+n.resource+" has an XML declaration. We'll assume it's XML but its content-type wasn't XML.\n"),new N(this.response).parse(e,t,n,r)):t.slice(0,500).match(/xmlns:/)?(e.addStatus(n.req,"May have an XML namespace. We'll assume it's XML but its content-type wasn't XML.\n"),new N(this.response).parse(e,t,n,r)):(e.addStatus(n.req,"Plain text document, no known RDF semantics."),e.doneFetch(n,this.response))}}],[{key:"toString",value:function(){return"TextHandler"}},{key:"register",value:function(e){e.mediatypes["text/plain"]={q:.5}}}]),t}();R.pattern=new RegExp("text/plain");var C=function(e){function t(){return c(this,t),a(this,s(t).apply(this,arguments))}return u(t,S),o(t,[{key:"parse",value:function(e,t,n,r){var i=e.store,o=d(i,i,n.original.uri,n.original.uri,null,null,"",null);try{o.loadBuf(t)}catch(t){var a="Error trying to parse "+n.resource+" as Notation3:\n"+t;return e.failFetch(n,a,"parse_error",r)}return e.addStatus(n.req,"N3 parsed: "+o.statementCount+" triples in "+o.lines+" lines."),e.store.add(n.original,j.rdf("type"),j.link("RDFDocument"),e.appNode),e.doneFetch(n,this.response)}}],[{key:"toString",value:function(){return"N3Handler"}},{key:"register",value:function(e){e.mediatypes["text/n3"]={q:"1.0"},e.mediatypes["text/turtle"]={q:1}}}]),t}();C.pattern=new RegExp("(application|text)/(x-)?(rdf\\+)?(n3|turtle)");var L={RDFXMLHandler:E,XHTMLHandler:O,XMLHandler:N,HTMLHandler:I,TextHandler:R,N3Handler:C},A=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(c(this,e),this.store=t||new f,this.timeout=r.timeout||3e4,this._fetch=r.fetch||_,!this._fetch)throw new Error("No _fetch function availble for Fetcher");this.appNode=this.store.bnode(),this.store.fetcher=this,this.requested={},this.timeouts={},this.redirectedTo={},this.fetchQueue={},this.fetchCallbacks={},this.nonexistent={},this.lookedUp={},this.handlers=[],this.mediatypes={"image/*":{q:.9},"*/*":{q:.1}},w.callbackify(this,["request","fail","refresh","retract","done"]),Object.keys(L).map(function(e){return n.addHandler(L[e])})}return o(e,[{key:"load",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(n=Object.assign({},n),e instanceof Array)return Promise.all(e.map(function(e){return t.load(e,Object.assign({},n))}));var r=e.uri||e;return r=r.split("#")[0],n=this.initFetchOptions(r,n),this.pendingFetchPromise(r,n.baseURI,n)}},{key:"pendingFetchPromise",value:function(e,t,n){var r,i=this;return!n.force&&this.fetchQueue[t]?r=this.fetchQueue[t]:(r=Promise.race([this.setRequestTimeout(e,n),this.fetchUri(e,n)]),this.fetchQueue[t]=r,this.cleanupFetchRequest(t,n,this.timeout)),r.then(function(t){return e in i.timeouts&&(i.timeouts[e].forEach(clearTimeout),delete i.timeouts[e]),t})}},{key:"cleanupFetchRequest",value:function(e,t,n){var r=this;this.timeouts[e]=(this.timeouts[e]||[]).concat(setTimeout(function(){r.isPending(e)||delete r.fetchQueue[e]},n))}},{key:"initFetchOptions",value:function(t,n){var r=this.store;!n.method||"GET"===n.method.toUpperCase()||(n.force=!0),n.resource=r.sym(t),n.baseURI=n.baseURI||t,n.original=r.sym(n.baseURI),n.req=r.bnode(),n.headers=n.headers||{},n.contentType&&(n.headers["content-type"]=n.contentType),n.force&&(n.cache="no-cache");var i=this.acceptString();n.headers.accept=i;var o=e.offlineOverride(t);n.requestedURI=o,e.withCredentials(o,n)&&(n.credentials="include");var a=e.proxyIfNecessary(o);return o!==a&&(n.proxyUsed=!0),n.actualProxyURI=a,n}},{key:"fetchUri",value:function(t,n){var r=this;if(!t)return Promise.reject(new Error("Cannot fetch an empty uri"));if(e.unsupportedProtocol(t))return this.failFetch(n,"fetcher: Unsupported protocol","unsupported_protocol");var i=this.getState(t);if(n.force)delete this.nonexistent[t];else{if("fetched"===i)return Promise.resolve(this.doneFetch(n,{status:200,ok:!0,statusText:"Already loaded into quadstore."}));if("failed"===i&&404===this.requested[t]){var o="Previously failed: "+this.requested[t],a={url:t,status:this.requested[t],statusText:o,responseText:o,headers:{},ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return this.failFetch(n,o,this.requested[t],a)}}this.fireCallbacks("request",[t]),this.requested[t]=!0,n.noMeta||this.saveRequestMetadata(t,n);var s=n.actualProxyURI;return this._fetch(s,n).then(function(e){return r.handleResponse(e,t,n)},function(e){var t={url:s,status:999,statusText:(e.name||"network failure")+": "+(e.errno||e.code||e.type),responseText:e.message,headers:{},ok:!1,body:null,bodyUsed:!1,size:0,timeout:0};return console.log("Fetcher: <"+s+"> Non-HTTP fetch error: "+e),r.failFetch(n,"fetch failed: "+e,999,t)})}},{key:"nowOrWhenFetched",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};e=e.uri||e,"function"==typeof t?n=t:void 0===t||(t instanceof p?r.referringTerm=t:r=t),this.load(e,r).then(function(t){if(n)if(t)if(t.ok)n(!0,"OK",t);else{var r="HTTP error: Status "+t.status+" ("+t.statusText+")";t.responseText&&(r+=" "+t.responseText),console.log(r+" fetching "+e),n(!1,r,t)}else{var i="@@ nowOrWhenFetched: no response object!";console.log(i),n(!1,i)}},function(t){var r=t.message||t.statusText;r="Failed to load <"+e+"> "+r,console.log(r),t.response&&t.response.status&&(r+=" status: "+t.response.status),n(!1,r,t.response)})}},{key:"addStatus",value:function(e,t){var n=new Date;t="["+n.getHours()+":"+n.getMinutes()+":"+n.getSeconds()+"."+n.getMilliseconds()+"] "+t;var r=this.store,i=r.the(e,j.link("status"));i&&i.append?i.append(r.literal(t)):h.warn("web.js: No list to add to: "+i+","+t)}},{key:"failFetch",value:function(e,t,n,r){this.addStatus(e.req,t),e.noMeta||this.store.add(e.original,j.link("error"),t);var i=(e.method||"GET").toUpperCase();("GET"===i||"HEAD"===i)&&(e.resource.sameTerm(e.original),this.requested[b.docpart(e.original.uri)]=n,this.fireCallbacks("fail",[e.original.uri,t]));var o=new Error("Fetcher: "+t);return o.status=n,o.statusText=t,o.response=r,Promise.reject(o)}},{key:"linkData",value:function(e,t,n,r,i){if(n){var o,a=this.store,s=a.sym(b.join(n,e.uri));if("alternate"===t||"seeAlso"===t||"meta"===t||"describedby"===t){if(s.uri===e.uri)return;o=j.rdfs("seeAlso")}else o="type"===t?a.sym("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"):a.sym(b.join(encodeURIComponent(t),"http://www.iana.org/assignments/link-relations/"));i?a.add(s,o,e,r):a.add(e,o,s,r)}}},{key:"parseLinkHeader",value:function(e,t,n){if(e)for(var r=/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g,i=e.match(/<[^>]*>\s*(\s*;\s*[^()<>@,;:"\/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g),o=0;o"),s=a[0].substring(1),u=a[1].match(r),l=0;l1&&void 0!==arguments[1]?arguments[1]:{};e=e.uri||e;var n=new p(e).doc();return t.contentType=t.contentType||"text/turtle",t.data=x(n,this.store,n.uri,t.contentType),this.webOperation("PUT",e,t)}},{key:"webCopy",value:function(e,t,n){var r=this;return this.webOperation("GET",e).then(function(e){return r.webOperation("PUT",t,{data:e.responseText,contentType:n})})}},{key:"delete",value:function(e,t){var n=this;return this.webOperation("DELETE",e,t).then(function(t){return n.requested[e]=404,n.nonexistent[e]=!0,n.unload(n.store.sym(e)),t})}},{key:"createIfNotExists",value:function(e){return new Promise(function(t,n){kb.fetcher.load(e).then(function(n){console.log("createIfNotExists doc exists, all good "+e),t(n)},function(r){404===r.response.status?(console.log("createIfNotExists doc does NOT exist, will create... "+e),kb.fetcher.webOperation("PUT",e.uri,{data:"",contentType:"text/turtle"}).then(function(n){delete kb.fetcher.requested[e.uri],console.log("createIfNotExists doc created ok "+e),t(n)},function(t){console.log("createIfNotExists doc FAILED: "+e+": "+t),n(t)})):(console.log("createIfNotExists doc load error NOT 404: "+e+": "+r),n(r))})})}},{key:"createContainer",value:function(e,t,n){var r={"content-type":"text/turtle",link:j.ldp("BasicContainer")+'; rel="type"'};t&&(r.slug=t);var i={headers:r};return n&&(i.body=n),this.webOperation("POST",e,i)}},{key:"webOperation",value:function(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n=n.uri||n,r.method=t,r.body=r.data||r.body,r.force=!0;var i=this;if(r.body&&!r.contentType)throw new Error("Web operation sending data must have a defined contentType.");return r.contentType&&(r.headers=r.headers||{},r.headers["content-type"]=r.contentType),e.withCredentials(n,r)&&(r.credentials="include"),new Promise(function(e,o){i._fetch(n,r).then(function(r){if(r.ok)"PUT"!==t&&"PATCH"!==t&&"POST"!==t&&"DELETE"!==t||delete i.requested[n],r.body?r.text().then(function(t){r.responseText=t,e(r)}):e(r);else{var a="Web error: "+r.status;r.statusText&&(a+=" ("+r.statusText+")"),a+=" on "+t+" of <"+n+">",r.responseText&&(a+=": "+r.responseText);var s=new Error(a);s.response=r,o(s)}},function(e){o(new Error("Fetch error for "+t+" of <"+n+">:"+e))})})}},{key:"lookUpThing",value:function(e,t){var n=this,r=this.store.uris(e);return(r=r.map(function(e){return b.docpart(e)})).forEach(function(e){n.lookedUp[e]=!0}),this.load(r,{referringTerm:t})}},{key:"getHeader",value:function(e,t){for(var n=this.store,r=n.each(void 0,j.link("requestedURI"),e.uri),i=0;i=400)return 404===e.status&&(this.nonexistent[n.original.uri]=!0,this.nonexistent[t]=!0),this.saveErrorResponse(e,s).then(function(){var t=n.resource+" "+e.statusText;return r.failFetch(n,t,e.status,e)});var c=null,f=null;if(l&&(f=b.join(l,t))!==t&&(c=f),200===e.status){this.addType(j.link("Document"),a,i,t),c&&this.addType(j.link("Document"),a,i,c),n.clearPreviousData&&i.removeDocument(n.resource);var h=u.includes("image/")||u.includes("application/pdf");u&&h&&(this.addType(i.sym("http://purl.org/dc/terms/Image"),a,i,t),c&&this.addType(i.sym("http://purl.org/dc/terms/Image"),a,i,c))}if(l){if(!n.force&&c&&"done"===this.requested[f])return this.doneFetch(n,e);this.requested[f]=!0}this.parseLinkHeader(o.get("link"),n.original,a);var d=this.handlerForContentType(u,e);return d?e.text().then(function(t){return e.responseText=t,d.parse(r,t,n,e)}):(this.addStatus(a,"Fetch over. No data handled."),this.doneFetch(n,e))}},{key:"saveErrorResponse",value:function(e,t){var n=this.store;return e.text().then(function(e){e.length>10&&n.add(t,j.http("content"),n.literal(e),t)})}},{key:"handlerForContentType",value:function(e,t){if(!e)return null;var n=this.handlers.find(function(t){return e.match(t.pattern)});return n?new n(t):null}},{key:"guessContentType",value:function(e){return T[e.split(".").pop()]}},{key:"normalizedContentType",value:function(e,t){if(e.forceContentType)return e.forceContentType;var n=t.get("content-type");if(!n||n.includes("application/octet-stream")){var r=this.guessContentType(e.resource.uri);if(r)return r}var i=b.protocol(e.resource.uri);return!n&&["file","chrome"].includes(i)?"text/xml":n}},{key:"redirectToProxy",value:function(e,t){var n=this;this.addStatus(t.req,"BLOCKED -> Cross-site Proxy to <"+e+">"),t.proxyUsed=!0;var r=this.store,i=t.req;t.noMeta||(r.add(i,j.link("redirectedTo"),r.sym(e),i),this.addStatus(i,"redirected to new request")),this.requested[t.resource.uri]="redirected",this.redirectedTo[t.resource.uri]=e;var o=Object.assign({},t);return o.baseURI=t.resource.uri,this.fetchUri(e,o).then(function(e){return o.noMeta||r.add(i,j.link("redirectedRequest"),o.req,n.appNode),e})}},{key:"setRequestTimeout",value:function(e,t){var n=this;return new Promise(function(r){n.timeouts[e]=(n.timeouts[e]||[]).concat(setTimeout(function(){!n.isPending(e)||t.retriedWithNoCredentials||t.proxyUsed||r(n.failFetch(t,"Request to ".concat(e," timed out"),"timeout"))},n.timeout))})}},{key:"addFetchCallback",value:function(e,t){this.fetchCallbacks[e]?this.fetchCallbacks[e].push(t):this.fetchCallbacks[e]=[t]}},{key:"acceptString",value:function(){var e="";for(var t in this.mediatypes)for(var n in""!==e&&(e+=", "),e+=t,this.mediatypes[t])e+=";"+n+"="+this.mediatypes[t][n];return e}}],[{key:"crossSiteProxy",value:function(t){return e.crossSiteProxyTemplate?e.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(t)):void 0}},{key:"offlineOverride",value:function(e){var t,n=e;return"undefined"!=typeof window&&window.panes&&(t=window.panes.UI)&&t.preferences&&t.preferences.get("offlineModeUsingLocalhost")&&"http://"===n.slice(0,7)&&"localhost/"!==n.slice(7,17)&&(n="http://localhost/"+n.slice(7),h.warn("Localhost kludge for offline use: actually getting <"+n+">")),n}},{key:"proxyIfNecessary",value:function(t){var n;if("undefined"!=typeof window&&window.panes&&(n=window.panes.UI)&&n.isExtension)return t;if("undefined"!=typeof $SolidTestEnvironment&&$SolidTestEnvironment.localSiteMap){var r=function e(t,n){var r=n[t.shift()];return r?"string"==typeof r?r+t.join("/"):t?e(t,r):null:null}(t.split("/").slice(2),$SolidTestEnvironment.localSiteMap);if(r)return r}return e.crossSiteProxyTemplate&&"undefined"!=typeof document&&document.location&&"https:"===(""+document.location).slice(0,6)&&"http:"===t.slice(0,5)?e.crossSiteProxyTemplate.replace("{uri}",encodeURIComponent(t)):t}},{key:"unsupportedProtocol",value:function(e){var t=b.protocol(e);return"tel"===t||"mailto"===t||"urn"===t}},{key:"withCredentials",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.startsWith("https:");return void 0!==t.withCredentials&&(n=t.withCredentials),n}}]),e}();e.exports=A,e.exports.HANDLERS=L,e.exports.CONTENT_TYPE_BY_EXT=T},function(e,t,n){e.exports=function(e,t,n,o,a,s){n=n||e.uri,s=s||{},o=o||"text/turtle";try{var u=i(t);s.flags&&u.setFlags(s.flags);var l,c=t.statementsMatching(void 0,void 0,void 0,e);switch(u.suggestNamespaces(t.namespaces),u.setBase(n),o){case"application/rdf+xml":return f(null,u.statementsToXML(c));case"text/n3":case"application/n3":return f(null,u.statementsToN3(c));case"text/turtle":case"application/x-turtle":return u.setFlags("si"),f(null,u.statementsToN3(c));case"application/n-triples":return u.setFlags("deinprstux"),f(null,u.statementsToNTriples(c));case"application/ld+json":u.setFlags("deinprstux"),l=u.statementsToNTriples(c),r.convertToJson(l,a);break;case"application/n-quads":case"application/nquads":return u.setFlags("deinprstux q"),f(null,u.statementsToNTriples(c));default:throw new Error("Serialize: Content-type "+o+" not supported for data write.")}}catch(e){if(a)return a(e);throw e}function f(e,t){return a?void a(e,t):t}};var r=n(38),i=n(34)},function(e,t,n){var r=n(0),i=n(6),o=n(2),a=n(3),s=n(37),u=function(){var e=function(e){this.flags="",this.base=null,this.prefixes=[],this.namespaces=[],this.suggestPrefix("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#"),this.suggestPrefix("xml","reserved:reservedForFutureUse"),this.namespacesUsed=[],this.keywords=["a"],this.prefixchars="abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",this.incoming=null,this.formulas=[],this.store=e};e.prototype.setBase=function(e){return this.base=e,this},e.prototype.setFlags=function(e){return this.flags=e||"",this},e.prototype.toStr=function(e){var t=e.toNT();return"Graph"===e.termType&&(this.formulas[t]=e),t},e.prototype.fromStr=function(e){if("{"===e[0]){var t=this.formulas[e];return t||console.log("No formula object for "+e),t}return this.store.fromNT(e)},e.prototype.suggestPrefix=function(e,t){"default"!==e.slice(0,7)&&"ns"!==e.slice(0,2)&&e&&t&&(e in this.namespaces||t in this.prefixes||(this.prefixes[t]=e,this.namespaces[e]=t))},e.prototype.suggestNamespaces=function(e){for(var t in e)return this.suggestPrefix(t,e[t]),this},e.prototype.checkIntegrity=function(){var e,t;for(e in this.namespaces)if(this.prefixes[this.namespaces[e]]!==e)throw new Error("Serializer integity error 1: "+e+", "+this.namespaces[e]+", "+this.prefixes[this.namespaces[e]]+"!");for(t in this.prefixes)if(this.namespaces[this.prefixes[t]]!==t)throw new Error("Serializer integity error 2: "+t+", "+this.prefixs[t]+", "+this.namespaces[this.prefixes[t]]+"!")},e.prototype.makeUpPrefix=function(t){var n=t;var r=function(n){return!!e.prototype.validPrefix.test(n)&&"ns"!==n&&!(n in this.namespaces)&&(this.prefixes[t]=n,this.namespaces[n]=t,n)}.bind(this);"#/".indexOf(n[n.length-1])>=0&&(n=n.slice(0,-1));var i=n.lastIndexOf("/");i>=0&&(n=n.slice(i+1));for(var o=0;o?@[\\]^`{|}~",e.prototype._notNameChars=e.prototype._notQNameChars+":",e.prototype.explicitURI=function(e){return"<"+(e=this.flags.indexOf("r")<0&&this.base?o.refTo(this.base,e):this.flags.indexOf("u")>=0?function(e){for(var t,n="",r=0;r65535?"\\U"+("00000000"+t.toString(16)).slice(-8):t>126?"\\u"+("0000"+t.toString(16)).slice(-4):e[r];return n}(e):encodeURI(e))+">"},e.prototype.statementsToNTriples=function(e){var t=e.slice();t.sort();for(var n="",r="http://www.w3.org/1999/02/22-rdf-syntax-ns#",o=this,a=this.store,s=function e(t){if("Collection"!==t.termType)return o.atomicTermToN3(t);for(var s=t.elements,u=a.sym(r+"nill"),l=s.length-1;l>=0;l--){var c=new i;n+=e(c)+" "+e(a.sym(r+"first"))+" "+e(s[l])+".\n",n+=e(c)+" "+e(a.sym(r+"rest"))+" "+e(u)+".\n",u=c}return o.atomicTermToN3(u)},u=0;u=0&&(c+=s(l.why)+" "),n+=c+=".\n"}return n},e.prototype.statementsToN3=function(t){var n=this.store,r={"http://www.w3.org/1999/02/22-rdf-syntax-ns#type":"aaa:00"};t.sort(function(e,t){return a.heavyCompareSPO(e,t,n,r)}),this.base&&!this.defaultNamespace&&(this.defaultNamespace=this.base+"#");var i={};this.flags.indexOf("s")<0&&(i["http://www.w3.org/2002/07/owl#sameAs"]="="),this.flags.indexOf("t")<0&&(i["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"]="a"),this.flags.indexOf("i")<0&&(i["http://www.w3.org/2000/10/swap/log#implies"]="=>");var o=function(e){for(var t="",n=0;n=0){r=r.slice(0,-1)+u+"\n",i+=1;continue}if(i<4*n+4||i+u.length+1<80&&";.".indexOf(r[r.length-2])<0)r=r.slice(0,-1)+" "+u+"\n",i+=u.length+1;else{var f=o(4*n)+u;r+=f+"\n",i=f.length,n<0&&(r+="\n",i=1e5)}}}return r}(p)},e.prototype.atomicTermToN3=function(e,t){switch(e.termType){case"BlankNode":case"Variable":return e.toNT();case"Literal":var n=e.value;if("string"!=typeof n)throw new TypeError("Value of RDF literal node must be a string");if(e.datatype&&this.flags.indexOf("x")<0)switch(e.datatype.uri){case"http://www.w3.org/2001/XMLSchema#integer":return n;case"http://www.w3.org/2001/XMLSchema#decimal":return n.indexOf(".")<0&&(n+=".0"),n;case"http://www.w3.org/2001/XMLSchema#double":return n.indexOf(".")<0&&(n+=".0"),n.indexOf("e")<0&&(n+="e0"),n;case"http://www.w3.org/2001/XMLSchema#boolean":return"1"===e.value?"true":"false"}var r=this.stringToN3(e.value);return e.language?r+="@"+e.language:e.datatype.equals(s.string)||(r+="^^"+this.atomicTermToN3(e.datatype,t)),r;case"NamedNode":return this.symbolToN3(e);default:throw new Error("Internal: atomicTermToN3 cannot handle "+e+" of termType: "+e.termType)}},e.prototype.validPrefix=new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/),e.prototype.forbidden1=new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm),e.prototype.forbidden3=new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm),e.prototype.stringToN3=function(t,n){n||(n="e");var r,i,o,a,s,u="";for(t.length>20&&'"'!==t.slice(-1)&&n.indexOf("n")<0&&(t.indexOf("\n")>0||t.indexOf('"')>0)?(a='"""',s=e.prototype.forbidden3):(a='"',s=e.prototype.forbidden1),r=0;r=0?u+="\\"+'bfrtvn\\"'[o]:n.indexOf("e")>=0?u+="\\u"+("000"+l.charCodeAt(0).toString(16).toLowerCase()).slice(-4):u+=l,r=i+1}return a+u+t.slice(r)+a},e.prototype.symbolToN3=function(t){var n=t.uri,r=n.indexOf("#");if(r<0&&this.flags.indexOf("/")<0&&(r=n.lastIndexOf("/")),r>=0&&this.flags.indexOf("p")<0&&(0===n.indexOf("http")||0===n.indexOf("ws")||0===n.indexOf("file"))){for(var i=!0,o=r+1;o=0){i=!1;break}if(i){var a=n.slice(r+1),s=n.slice(0,r+1);if(this.defaultNamespace&&this.defaultNamespace===s&&this.flags.indexOf("d")<0)return this.flags.indexOf("k")>=0&&this.keyords.indexOf(a)<0?a:":"+a;var u=this.prefixes[s];if(u||(u=this.makeUpPrefix(s)),u)return this.namespacesUsed[s]=!0,u+":"+a}}return this.explicitURI(n)},e.prototype.writeStore=function(e){var t=this.store,n=t.fetcher,r=n&&n.appNode,i=this.store.index[3];for(var o in i){var a=t.fromNT(o);r&&a.sameTerm(r)||e("\n"+this.atomicTermToN3(a)+" "+this.atomicTermToN3(t.sym("http://www.w3.org/2000/10/swap/log#semantics"))+" { "+this.statementsToN3(t.statementsMatching(void 0,void 0,void 0,a))+" }.\n")}t.statementsMatching(void 0,t.sym("http://www.w3.org/2007/ont/link#requestedURI")).map(function(n){e("\n<"+n.object.value+"> log:metadata {\n");var r=t.statementsMatching(void 0,void 0,void 0,n.subject);e(this.statementsToN3(this.statementsToN3(r))),e("}.\n")});var s=[];r&&s.push(r);var u=[];s.map(function(e){u=u.concat(t.statementsMatching(void 0,void 0,void 0,e))}),e(this.statementsToN3(u))},e.prototype.statementsToXML=function(t){var n=[];n["http://www.w3.org/1999/02/22-rdf-syntax-ns#"]=!0;var i="http://www.w3.org/1999/02/22-rdf-syntax-ns#_",o=function(e){for(var t="",n=0;n',h(a.object,t),""]):l.concat(["<"+o+' rdf:nodeID="'+a.object.toNT().slice(2)+'"/>']);break;case"NamedNode":l=l.concat(["<"+o+' rdf:resource="'+f(a.object)+'"/>']);break;case"Literal":l=l.concat(["<"+o+(a.object.datatype.equals(s.string)?"":' rdf:datatype="'+c(a.object.datatype.uri)+'"')+(a.object.language?' xml:lang="'+a.object.language+'"':"")+">"+c(a.object.value)+""]);break;case"Collection":l=l.concat(["<"+o+' rdf:parseType="Collection">',d(a.object,t),""]);break;default:throw new Error("Can't serialize object of type "+a.object.termType+" into XML")}}else n=a.object;var b=n?v(n):"rdf:Description",w="";return"BlankNode"===e.termType?t.incoming[e]&&1===t.incoming[e].length||(w=' rdf:nodeID="'+e.toNT().slice(2)+'"'):w=' rdf:about="'+f(e)+'"',["<"+b+w+">"].concat([l]).concat([""])}.bind(this);function d(e,t){for(var n=[],r=0;r',""]):n.concat(["<"+v(o.predicate)+' rdf:parseType="Resource">',p(o.object,t),""]);break;case"NamedNode":n=n.concat(["<"+v(o.predicate)+' rdf:resource="'+f(o.object)+'"/>']);break;case"Literal":n=n.concat(["<"+v(o.predicate)+(o.object.datatype.equals(s.string)?"":' rdf:datatype="'+c(o.object.datatype.value)+'"')+(o.object.language?' xml:lang="'+o.object.language+'"':"")+">"+c(o.object.value)+""]);break;case"Collection":n=n.concat(["<"+v(o.predicate)+' rdf:parseType="Collection">',d(o.object,t),""]);break;default:throw new Error("Can't serialize object of type "+o.object.termType+" into XML")}}return n}.bind(this);var v=function(t){var r=t.uri,i=r.indexOf("#");if(i<0&&this.flags.indexOf("/")<0&&(i=r.lastIndexOf("/")),i<0)throw new Error("Cannot make qname out of <"+r+">");for(var o=i+1;o=0)throw new Error('Invalid character "'+r[o]+'" cannot be in XML qname for URI: '+r);var a=r.slice(i+1),s=r.slice(0,i+1);if(this.defaultNamespace&&this.defaultNamespace===s&&this.flags.indexOf("d")<0)return a;var u=this.prefixes[s];return u||(u=this.makeUpPrefix(s)),n[s]=!0,u+":"+a}.bind(this),y=l(t),g=""],-1)};return function(t){return new e(t)}}();e.exports=u},function(e,t,n){function r(e,t){for(var n=0;n=0){var a=t.substring(0,o);if(""===a)return(i=n[""])?i+t.substring(o+1):null;if("_"===a)return"_:"+t.substring(o+1);if(e.NCNAME.test(a)&&(i=n[a]))return i+t.substring(o+1)}return null}},{key:"parseCURIEOrURI",value:function(e,t,n){var r=this.parseCURIE(e,t,n);return r||this.resolveAndNormalize(n,e)}},{key:"parsePredicate",value:function(e,t,n,r,i,o){if(""===e)return null;var a=this.parseTermOrCURIEOrAbsURI(e,t,o?null:n,r,i);return a&&0===a.indexOf("_:")?null:a}},{key:"parsePrefixMappings",value:function(e,t){for(var n=this.tokenize(e),r=null,i=0;i=0&&(e=e.substring(0,t)),n&&n.baseURIMap&&(e=n.baseURIMap(e)),e};for(i.push({current:t,context:this.push(null,o(t.baseURI))});i.length>0;){var a=i.shift();if(a.parent){if(a.context.parent&&a.context.parent.listMapping===a.listMapping)continue;for(var s in a.listMapping){var l=a.listMapping[s];if(0!==l.length){for(var f=[],h=0;h0){S=O;var N=r.spec;this.addTriple(p,N,"http://www.w3.org/ns/rdfa#usesVocabulary",{type:e.objectURI,value:S})}else S=this.vocabulary}for(var I=0;I0?P:null}var M,F,B=p.getAttributeNode("rel"),q=p.getAttributeNode("rev"),z=p.getAttributeNode("typeof"),H=p.getAttributeNode("property"),V=p.getAttributeNode("datatype"),X=this.inHTMLMode?p.getAttributeNode("datetime"):null,W=p.getAttributeNode("content"),J=p.getAttributeNode("about"),Y=p.getAttributeNode("src"),Q=p.getAttributeNode("resource"),$=p.getAttributeNode("href"),G=p.getAttributeNode("inlist"),Z=[];if(B){F=this.tokenize(B.value);for(var K=0;K=0?t+=e.nodeName.split(":")[1]:t+=e.nodeName),t}.bind(this),o=!0;e.parent;){var a=e.element,s=a.attributes;if(a.nodeType===t.nodeType.TEXT||a.nodeType===t.nodeType.CDATA_SECTION)e.parent.nodeType===e.NODE&&(e.addArc(t.ns.RDF+"value"),e=this.buildFrame(e)),e.addLiteral(a.nodeValue);else if(i(a)!==t.ns.RDF+"RDF")if(e.parent&&e.parent.collection&&(e.addCollectionArc(),(e=this.buildFrame(e,e.element)).parent.element=null),e.parent&&e.parent.nodeType&&e.parent.nodeType!==e.ARC){e.addArc(i(a)),this.reify&&(n=this.getAttributeNodeNS(a,t.ns.RDF,"ID"))&&(e.rdfid=n.nodeValue,a.removeAttributeNode(n));var u=this.getAttributeNodeNS(a,t.ns.RDF,"parseType"),l=this.getAttributeNodeNS(a,t.ns.RDF,"datatype");if(l&&(e.datatype=l.nodeValue,a.removeAttributeNode(l)),u){var c=u.nodeValue;"Literal"===c?(e.datatype=t.ns.RDF+"XMLLiteral",(e=this.buildFrame(e)).addLiteral(a.childNodes),o=!1):"Resource"===c?((e=this.buildFrame(e,e.element)).parent.element=null,e.addBNode()):"Collection"===c&&((e=this.buildFrame(e,e.element)).parent.element=null,e.addCollection()),a.removeAttributeNode(u)}if(0!==s.length){var f=this.getAttributeNodeNS(a,t.ns.RDF,"resource"),h=this.getAttributeNodeNS(a,t.ns.RDF,"nodeID");e=this.buildFrame(e),f?(e.addNode(f.nodeValue),a.removeAttributeNode(f)):h?(e.addBNode(h.nodeValue),a.removeAttributeNode(h)):e.addBNode();for(var d=s.length-1;d>=0;d--){var p=this.buildFrame(e);p.addArc(i(s[d])),i(s[d])===t.ns.RDF+"type"?this.buildFrame(p).addNode(s[d].nodeValue):this.buildFrame(p).addLiteral(s[d].nodeValue)}}else 0===a.childNodes.length&&this.buildFrame(e).addLiteral("")}else{var v=this.getAttributeNodeNS(a,t.ns.RDF,"about");if(n=this.getAttributeNodeNS(a,t.ns.RDF,"ID"),v&&n)throw new Error("RDFParser: "+a.nodeName+" has both rdf:id and rdf:about. Halting. Only one of these properties may be specified on a node.");if(!v&&n)e.addNode("#"+n.nodeValue),a.removeAttributeNode(n);else if(null==v&&null==n){var y=this.getAttributeNodeNS(a,t.ns.RDF,"nodeID");y?(e.addBNode(y.nodeValue),a.removeAttributeNode(y)):e.addBNode()}else e.addNode(v.nodeValue),a.removeAttributeNode(v);var g=this.getAttributeNodeNS(a,t.ns.RDF,"type");t.ns.RDF+"Description"!==i(a)&&(g={nodeValue:i(a)}),null!=g&&(this.store.add(e.node,this.store.sym(t.ns.RDF+"type"),this.store.sym(r.join(g.nodeValue,e.base)),this.why),g.nodeName&&a.removeAttributeNode(g));for(var m=s.length-1;m>=0;m--)this.store.add(e.node,this.store.sym(i(s[m])),this.store.literal(s[m].nodeValue,e.lang),this.why)}for(a=e.element;e.parent;){for(var b=e;null==a;)a=(e=e.parent).element;var w=a.childNodes&&a.childNodes[e.lastChild];if(w&&o){if((w.nodeType===t.nodeType.ELEMENT||w.nodeType===t.nodeType.TEXT||w.nodeType===t.nodeType.CDATA_SECTION)&&(w.nodeType!==t.nodeType.TEXT&&w.nodeType!==t.nodeType.CDATA_SECTION||1===a.childNodes.length)){e.lastChild++,e=this.buildFrame(b,a.childNodes[e.lastChild-1]);break}e.lastChild++}else{if(e.terminateFrame(),!(e=e.parent))break;a=e.element,o=!0}}}},this.cleanParser=function(){this.bnodes={},this.why=null},this.buildFrame=function(e,n){var i=this.frameFactory(this,e,n);if(e&&(i.base=e.base,i.lang=e.lang),!n||n.nodeType===t.nodeType.TEXT||n.nodeType===t.nodeType.CDATA_SECTION)return i;var o=n.attributes,a=n.getAttributeNode("xml:base");null!=a&&(i.base=a.nodeValue,n.removeAttribute("xml:base"));var s=n.getAttributeNode("xml:lang");null!=s&&(i.lang=s.nodeValue,n.removeAttribute("xml:lang"));for(var u=o.length-1;u>=0;u--)if("xml"===o[u].nodeName.substr(0,3)){if("xmlns:"===o[u].name.slice(0,6)){var l=o[u].nodeValue;this.base&&(l=r.join(l,this.base)),this.store.setPrefixForURI(o[u].name.slice(6),l)}n.removeAttributeNode(o[u])}return i}}},function(e,t,n){var r=n(0),i=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)};i.boolean=new r("http://www.w3.org/2001/XMLSchema#boolean"),i.dateTime=new r("http://www.w3.org/2001/XMLSchema#dateTime"),i.decimal=new r("http://www.w3.org/2001/XMLSchema#decimal"),i.double=new r("http://www.w3.org/2001/XMLSchema#double"),i.integer=new r("http://www.w3.org/2001/XMLSchema#integer"),i.langString=new r("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"),i.string=new r("http://www.w3.org/2001/XMLSchema#string"),e.exports=i},function(e,t,n){e.exports.convertToJson=function(e,t){var n,a=o.Parser(),s=o.Writer({format:"N-Quads"});r.waterfall([function(t){a.parse(e,t)},function(e,t,n){null!==e&&s.addTriple(e),"function"==typeof n&&s.end(n)},function(e,t){try{i.fromRDF(e,{format:"application/nquads"},t)}catch(e){t(e)}},function(e,r){n=JSON.stringify(e),t(null,n)}],function(e,r){t(e,n)})},e.exports.convertToNQuads=function(e,t){var n,i=o.Parser(),a=o.Writer({format:"N-Quads"});r.waterfall([function(t){i.parse(e,t)},function(e,t,n){null!==e&&a.addTriple(e),"function"==typeof n&&a.end(n)},function(e,r){t(null,n=e)}],function(e,r){t(e,n)})};var r=n(61),i=n(39),o=n(42)},function(e,t,n){(function(r,i,o,a){var s; +/** * A JavaScript implementation of the JSON-LD API. * * @author Dave Longley @@ -32,7 +33,46 @@ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */(function(){var p='undefined'!=typeof a&&a.versions&&a.versions.node,u=!p&&('undefined'!=typeof window||'undefined'!=typeof self);u&&'undefined'==typeof o&&('undefined'==typeof window?'undefined'==typeof self?'undefined'!=typeof $&&(o=$):o=self:o=window);var c=function(t){function e(){}function d(e){for(var t=[],n=Object.keys(e).sort(),a=0;a0)&&n.push(a[s]);var u=n.length>0;1===n.length&&(n=n[0]);if(re(t)){var l=G(r,"@graph"),c=t;t={},u&&(t["@context"]=n),t[l]=c}else if(ne(t)&&u){var c=t;for(var f in t={"@context":n},c)t[f]=c[f]}i(null,t,r)}(null,a,t,r)})})},e.expand=function(t,n,r){if(arguments.length<1)return e.nextTick(function(){r(new TypeError("Could not expand, too few arguments."))});function i(e){"base"in n||(n.base=e.documentUrl||"");var t={document:ve(e.document),remoteContext:{"@context":e.contextUrl}};if("expandContext"in n){var i=ve(n.expandContext);t.expandContext="object"==typeof i&&"@context"in i?i:{"@context":i}}ge(t,n,function(e,t){if(e)return r(e);var i;try{var o=new R,a=ee(n),s=t.document,u=t.remoteContext["@context"];t.expandContext&&(a=o.processContext(a,t.expandContext["@context"],n)),u&&(a=o.processContext(a,u,n)),ne(i=o.expand(a,null,s,n,!1))&&"@graph"in i&&1===Object.keys(i).length?i=i["@graph"]:null===i&&(i=[]),re(i)||(i=[i])}catch(e){return r(e)}r(null,i)})}"function"==typeof n&&(r=n,n={}),"documentLoader"in(n=n||{})||(n.documentLoader=e.loadDocument),"keepFreeFloatingNodes"in n||(n.keepFreeFloatingNodes=!1),e.nextTick(function(){if("string"!=typeof t)i({contextUrl:null,documentUrl:null,document:t});else{var e=function(e,t){if(e)return r(e);try{if(!t.document)throw new I("No remote document found at the given URL.","jsonld.NullRemoteDocument");"string"==typeof t.document&&(t.document=JSON.parse(t.document))}catch(e){return r(new I("Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.","jsonld.LoadDocumentError",{code:"loading document failed",cause:e,remoteDoc:t}))}i(t)},o=n.documentLoader(t,e);o&&"then"in o&&o.then(e.bind(null,null),e)}})},e.flatten=function(t,n,r,i){if(arguments.length<1)return e.nextTick(function(){i(new TypeError("Could not flatten, too few arguments."))});"function"==typeof r?(i=r,r={}):"function"==typeof n&&(i=n,n=null,r={}),"base"in(r=r||{})||(r.base="string"==typeof t?t:""),"documentLoader"in r||(r.documentLoader=e.loadDocument),e.expand(t,r,function(t,o){if(t)return i(new I("Could not expand input before flattening.","jsonld.FlattenError",{cause:t}));var a;try{a=(new R).flatten(o)}catch(e){return i(e)}if(null===n)return i(null,a);r.graph=!0,r.skipExpansion=!0,e.compact(a,n,r,function(e,t){if(e)return i(new I("Could not compact flattened output.","jsonld.FlattenError",{cause:e}));i(null,t)})})},e.frame=function(t,n,r,i){if(arguments.length<2)return e.nextTick(function(){i(new TypeError("Could not frame, too few arguments."))});function o(n){var o,a=n.document;a?(o=a["@context"],n.contextUrl?(o?re(o)?o.push(n.contextUrl):o=[o,n.contextUrl]:o=n.contextUrl,a["@context"]=o):o=o||{}):o={},e.expand(t,r,function(t,n){if(t)return i(new I("Could not expand input before framing.","jsonld.FrameError",{cause:t}));var s=ve(r);s.isFrame=!0,s.keepFreeFloatingNodes=!0,e.expand(a,s,function(t,r){if(t)return i(new I("Could not expand frame before framing.","jsonld.FrameError",{cause:t}));var a;try{a=(new R).frame(n,r,s)}catch(e){return i(e)}s.graph=!0,s.skipExpansion=!0,s.link={},e.compact(a,o,s,function(t,n,r){if(t)return i(new I("Could not compact framed output.","jsonld.FrameError",{cause:t}));var o=G(r,"@graph"); +// remove @preserve from results +s.link={},n[o]= +/** * Removes the @preserve keywords as the last step of the framing algorithm. * * @param ctx the active context used to compact the input. @@ -40,25 +80,40 @@ * @param options the compaction options used. * * @return the resulting output. - */function R(e,n,a){if(H(n)){for(var r=[],o=0,i;oC(j,_))&&(_=j)}return null===_?a.vocab?t:P(e['@base'],t):_}function E(e,n,a){if(Z(a)){var r=t.getContextValue(e,n,'@type'),o=t.getContextValue(e,n,'@language'),i=t.getContextValue(e,n,'@container'),s='@index'in a&&'@index'!==i;if(!s&&(a['@type']===r||a['@language']===o))return a['@value'];var d=Object.keys(a).length,l=1===d||2===d&&'@index'in a&&!s,p='@language'in e,u=V(a['@value']),c=e.mappings[n]&&null===e.mappings[n]['@language'];if(l&&(!p||!u||c))return a['@value'];var h={};return s&&(h[O(e,'@index')]=a['@index']),'@type'in a?h[O(e,'@type')]=O(e,a['@type'],null,{vocab:!0}):'@language'in a&&(h[O(e,'@language')]=a['@language']),h[O(e,'@value')]=a['@value'],h}var f=U(e,n,{vocab:!0}),r=t.getContextValue(e,n,'@type'),g=O(e,a['@id'],null,{vocab:'@vocab'===r});if('@id'===r||'@vocab'===r||'@graph'===f)return g;var h={};return h[O(e,'@id')]=g,h}function D(e,t,n,a){if(n in a){if(a[n])return;throw new De('Cyclical context definition detected.','jsonld.CyclicalContext',{code:'cyclic IRI mapping',context:t,term:n})}if(a[n]=!1,F(n))throw new De('Invalid JSON-LD syntax; keywords cannot be overridden.','jsonld.SyntaxError',{code:'keyword redefinition',context:t,term:n});if(''===n)throw new De('Invalid JSON-LD syntax; a term cannot be an empty string.','jsonld.SyntaxError',{code:'invalid term definition',context:t});e.mappings[n]&&delete e.mappings[n];var r=t[n];if(null===r||B(r)&&null===r['@id'])return e.mappings[n]=null,void(a[n]=!0);if(V(r)&&(r={"@id":r}),!B(r))throw new De('Invalid JSON-LD syntax; @context property values must be strings or objects.','jsonld.SyntaxError',{code:'invalid term definition',context:t});var o=e.mappings[n]={};if(o.reverse=!1,'@reverse'in r){if('@id'in r)throw new De('Invalid JSON-LD syntax; a @reverse term definition must not contain @id.','jsonld.SyntaxError',{code:'invalid reverse property',context:t});var i=r['@reverse'];if(!V(i))throw new De('Invalid JSON-LD syntax; a @context @reverse value must be a string.','jsonld.SyntaxError',{code:'invalid IRI mapping',context:t});var s=U(e,i,{vocab:!0,base:!1},t,a);if(!ne(s))throw new De('Invalid JSON-LD syntax; a @context @reverse value must be an absolute IRI or a blank node identifier.','jsonld.SyntaxError',{code:'invalid IRI mapping',context:t});o['@id']=s,o.reverse=!0}else if('@id'in r){var s=r['@id'];if(!V(s))throw new De('Invalid JSON-LD syntax; a @context @id value must be an array of strings or a string.','jsonld.SyntaxError',{code:'invalid IRI mapping',context:t});if(s!==n){if(s=U(e,s,{vocab:!0,base:!1},t,a),!ne(s)&&!F(s))throw new De('Invalid JSON-LD syntax; a @context @id value must be an absolute IRI, a blank node identifier, or a keyword.','jsonld.SyntaxError',{code:'invalid IRI mapping',context:t});o['@id']=s}}var d=n.indexOf(':');if(o._termHasColon=-1!==d,!('@id'in o))if(o._termHasColon){var l=n.substr(0,d);if(l in t&&D(e,t,l,a),e.mappings[l]){var p=n.substr(d+1);o['@id']=e.mappings[l]['@id']+p}else o['@id']=n}else{if(!('@vocab'in e))throw new De('Invalid JSON-LD syntax; @context terms must define an @id.','jsonld.SyntaxError',{code:'invalid IRI mapping',context:t,term:n});o['@id']=e['@vocab']+n}if(a[n]=!0,'@type'in r){var u=r['@type'];if(!V(u))throw new De('Invalid JSON-LD syntax; an @context @type values must be a string.','jsonld.SyntaxError',{code:'invalid type mapping',context:t});if('@id'!==u&&'@vocab'!==u){if(u=U(e,u,{vocab:!0,base:!1},t,a),!ne(u))throw new De('Invalid JSON-LD syntax; an @context @type value must be an absolute IRI.','jsonld.SyntaxError',{code:'invalid type mapping',context:t});if(0===u.indexOf('_:'))throw new De('Invalid JSON-LD syntax; an @context @type values must be an IRI, not a blank node identifier.','jsonld.SyntaxError',{code:'invalid type mapping',context:t})}o['@type']=u}if('@container'in r){var c=r['@container'];if('@list'!==c&&'@set'!==c&&'@index'!==c&&'@language'!==c)throw new De('Invalid JSON-LD syntax; @context @container value must be one of the following: @list, @set, @index, or @language.','jsonld.SyntaxError',{code:'invalid container mapping',context:t});if(o.reverse&&'@index'!==c&&'@set'!==c&&null!==c)throw new De('Invalid JSON-LD syntax; @context @container value for a @reverse type definition must be @index or @set.','jsonld.SyntaxError',{code:'invalid reverse property',context:t});o['@container']=c}if('@language'in r&&!('@type'in r)){var h=r['@language'];if(null!==h&&!V(h))throw new De('Invalid JSON-LD syntax; @context @language value must be a string or null.','jsonld.SyntaxError',{code:'invalid language mapping',context:t});null!==h&&(h=h.toLowerCase()),o['@language']=h}// disallow aliasing @context and @preserve -var s=o['@id'];if('@context'===s||'@preserve'===s)throw new De('Invalid JSON-LD syntax; @context and @preserve cannot be aliased.','jsonld.SyntaxError',{code:'invalid keyword alias',context:t})}function U(e,n,a,r,o){if(null===n||F(n))return n;if(n+='',r&&n in r&&!0!==o[n]&&D(e,r,n,o),a=a||{},a.vocab){var i=e.mappings[n];if(null===i)return null;if(i)return i['@id']}var s=n.indexOf(':');if(-1!==s){var d=n.substr(0,s),l=n.substr(s+1);if('_'===d||0===l.indexOf('//'))return n;r&&d in r&&D(e,r,d,o);var i=e.mappings[d];return i?i['@id']+l:n}if(a.vocab&&'@vocab'in e)return e['@vocab']+n;var p=n;return a.base&&(p=t.prependBase(e['@base'],p)),p}function A(e,n){if(null===e)return n;if(-1!==n.indexOf(':'))return n;V(e)&&(e=t.url.parse(e||''));var a=t.url.parse(n),r={protocol:e.protocol||''};if(null!==a.authority)r.authority=a.authority,r.path=a.path,r.query=a.query;else if(r.authority=e.authority,''===a.path)r.path=e.path,r.query=null===a.query?e.query:a.query;else{if(0===a.path.indexOf('/'))r.path=a.path;else{var o=e.path;''!==a.path&&(o=o.substr(0,o.lastIndexOf('/')+1),0d&&o[0]===s[0];)o.shift(),s.shift();var l='';if(0=i.length?'':i[n],d in o?o[d].push(r[s]):o[d]=[r[s]];for(var t in o)''!==t&&a(o,t,n+1)}function r(e,t,n,a){a in n||(n[a]=t)}function o(){var e={};return e['@base']=this['@base'],e.mappings=ae(this.mappings),e.clone=this.clone,e.inverse=null,e.getInverse=this.getInverse,'@language'in this&&(e['@language']=this['@language']),'@vocab'in this&&(e['@vocab']=this['@vocab']),e}var i=t.url.parse(e.base||'');return{"@base":i,mappings:{},inverse:null,getInverse:n,clone:o}}function F(e){return!!V(e)&&('@base'===e||'@context'===e||'@container'===e||'@default'===e||'@embed'===e||'@explicit'===e||'@graph'===e||'@id'===e||'@index'===e||'@language'===e||'@list'===e||'@omitDefault'===e||'@preserve'===e||'@requireAll'===e||'@reverse'===e||'@set'===e||'@type'===e||'@value'===e||'@vocab'===e)}function B(e){return'[object Object]'===Object.prototype.toString.call(e)}function q(e){return B(e)&&0===Object.keys(e).length}function H(e){return Array.isArray(e)}function z(e){if(!(V(e)||q(e))){var t=!1;if(H(e)){t=!0;for(var n=0;nEe)return a=new De('Maximum number of @context URLs exceeded.','jsonld.ContextUrlError',{code:'loading remote context failed',max:Ee}),s(a);var d={},l=function(){re(e,d,!0,r),s(null,e)};if(!re(e,d,!1,r))return l();var p=[];for(var u in d)!1===d[u]&&p.push(u);for(var c=p.length,h=0;h]*)>)|(_:(?:[A-Za-z0-9]+)))[ \t]+(?:<([^:]+:[^>]*)>)[ \t]+(?:(?:<([^:]+:[^>]*)>)|(_:(?:[A-Za-z0-9]+))|(?:"([^"\\]*(?:\\.[^"\\]*)*)"(?:(?:\^\^(?:<([^:]+:[^>]*)>))|(?:@([a-z]+(?:-[a-z0-9]+)*)))?))[ \t]*(?:\.|(?:(?:(?:<([^:]+:[^>]*)>)|(_:(?:[A-Za-z0-9]+)))[ \t]*\.))[ \t]*(?:#.*)?$/,b={},x=e.split(p),_=0,v=0,w;v':n.value,i+=' ',i+='IRI'===a.type?'<'+a.value+'>':a.value,i+=' ','IRI'===r.type)i+='<'+r.value+'>';else if('blank node'===r.type)i+=r.value;else{var s=r.value.replace(/\\/g,'\\\\').replace(/\t/g,'\\t').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/\"/g,'\\"');i+='"'+s+'"',r.datatype===Le?r.language&&(i+='@'+r.language):r.datatype!==ve&&(i+='^^<'+r.datatype+'>')}return null!==o&&void 0!==o&&(0===o.indexOf('_:')?i+=' '+o:i+=' <'+o+'>'),i+=' .\n',i}function le(e){for(var t={"@default":[]},n=e.getSubjects(),a=0,r;aarguments.length)return t.nextTick(function(){r(new TypeError('Could not compact, too few arguments.'))});if('function'==typeof a&&(r=a,a={}),a=a||{},null===n)return t.nextTick(function(){r(new De('The compaction context must not be null.','jsonld.CompactError',{code:'invalid local context'}))});if(null===e)return t.nextTick(function(){r(null,null)});'base'in a||(a.base='string'==typeof e?e:''),'compactArrays'in a||(a.compactArrays=!0),'graph'in a||(a.graph=!1),'skipExpansion'in a||(a.skipExpansion=!1),'documentLoader'in a||(a.documentLoader=t.loadDocument),'link'in a||(a.link=!1),a.link&&(a.skipExpansion=!0);var i=function(e,n,a){return n.skipExpansion?t.nextTick(function(){a(null,e)}):void t.expand(e,n,a)};i(e,a,function(e,i){if(e)return r(new De('Could not expand input before compaction.','jsonld.CompactError',{cause:e}));var s=M(a);t.processContext(s,n,a,function(e,t){if(e)return r(new De('Could not process context before compaction.','jsonld.CompactError',{cause:e}));var n;try{n=new Ue().compact(t,null,i,a)}catch(e){return r(e)}o(null,n,t,a)})})},t.expand=function(e,n,a){function r(e){'base'in n||(n.base=e.documentUrl||'');var t={document:ae(e.document),remoteContext:{"@context":e.contextUrl}};if('expandContext'in n){var r=ae(n.expandContext);t.expandContext='object'==typeof r&&'@context'in r?r:{"@context":r}}oe(t,n,function(e,t){if(e)return a(e);var r;try{var o=new Ue,i=M(n),s=t.document,d=t.remoteContext['@context'];t.expandContext&&(i=o.processContext(i,t.expandContext['@context'],n)),d&&(i=o.processContext(i,d,n)),r=o.expand(i,null,s,n,!1),B(r)&&'@graph'in r&&1===Object.keys(r).length?r=r['@graph']:null===r&&(r=[]),H(r)||(r=[r])}catch(e){return a(e)}a(null,r)})}return 1>arguments.length?t.nextTick(function(){a(new TypeError('Could not expand, too few arguments.'))}):void('function'==typeof n&&(a=n,n={}),n=n||{},!('documentLoader'in n)&&(n.documentLoader=t.loadDocument),!('keepFreeFloatingNodes'in n)&&(n.keepFreeFloatingNodes=!1),t.nextTick(function(){if('string'==typeof e){var t=function(e,t){if(e)return a(e);try{if(!t.document)throw new De('No remote document found at the given URL.','jsonld.NullRemoteDocument');'string'==typeof t.document&&(t.document=JSON.parse(t.document))}catch(e){return a(new De('Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.','jsonld.LoadDocumentError',{code:'loading document failed',cause:e,remoteDoc:t}))}r(t)},o=n.documentLoader(e,t);return void(o&&'then'in o&&o.then(t.bind(null,null),t))}r({contextUrl:null,documentUrl:null,document:e})}))},t.flatten=function(e,n,a,r){return 1>arguments.length?t.nextTick(function(){r(new TypeError('Could not flatten, too few arguments.'))}):void('function'==typeof a?(r=a,a={}):'function'==typeof n&&(r=n,n=null,a={}),a=a||{},!('base'in a)&&(a.base='string'==typeof e?e:''),!('documentLoader'in a)&&(a.documentLoader=t.loadDocument),t.expand(e,a,function(e,o){if(e)return r(new De('Could not expand input before flattening.','jsonld.FlattenError',{cause:e}));var i;try{i=new Ue().flatten(o)}catch(e){return r(e)}return null===n?r(null,i):void(a.graph=!0,a.skipExpansion=!0,t.compact(i,n,a,function(e,t){return e?r(new De('Could not compact flattened output.','jsonld.FlattenError',{cause:e})):void r(null,t)}))}))},t.frame=function(e,n,a,r){function o(n){var o=n.document,i;o?(i=o['@context'],n.contextUrl?(i?H(i)?i.push(n.contextUrl):i=[i,n.contextUrl]:i=n.contextUrl,o['@context']=i):i=i||{}):i={},t.expand(e,a,function(e,n){if(e)return r(new De('Could not expand input before framing.','jsonld.FrameError',{cause:e}));var s=ae(a);s.isFrame=!0,s.keepFreeFloatingNodes=!0,t.expand(o,s,function(e,a){if(e)return r(new De('Could not expand frame before framing.','jsonld.FrameError',{cause:e}));var o;try{o=new Ue().frame(n,a,s)}catch(e){return r(e)}s.graph=!0,s.skipExpansion=!0,s.link={},t.compact(o,i,s,function(e,t,n){if(e)return r(new De('Could not compact framed output.','jsonld.FrameError',{cause:e}));var a=O(n,'@graph');// remove @preserve from results -s.link={},t[a]=R(n,t[a],s),r(null,t)})})})}return 2>arguments.length?t.nextTick(function(){r(new TypeError('Could not frame, too few arguments.'))}):void('function'==typeof a&&(r=a,a={}),a=a||{},!('base'in a)&&(a.base='string'==typeof e?e:''),!('documentLoader'in a)&&(a.documentLoader=t.loadDocument),!('embed'in a)&&(a.embed='@last'),a.explicit=a.explicit||!1,!('requireAll'in a)&&(a.requireAll=!0),a.omitDefault=a.omitDefault||!1,t.nextTick(function(){if('string'==typeof n){var e=function(e,t){if(e)return r(e);try{if(!t.document)throw new De('No remote document found at the given URL.','jsonld.NullRemoteDocument');'string'==typeof t.document&&(t.document=JSON.parse(t.document))}catch(e){return r(new De('Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.','jsonld.LoadDocumentError',{code:'loading document failed',cause:e,remoteDoc:t}))}o(t)},t=a.documentLoader(n,e);return void(t&&'then'in t&&t.then(e.bind(null,null),e))}o({contextUrl:null,documentUrl:null,document:n})}))},t.link=function(e,n,a,r){var o={};n&&(o['@context']=n),o['@embed']='@link',t.frame(e,o,a,r)},t.objectify=function(e,n,a,r){'function'==typeof a&&(r=a,a={}),a=a||{},'base'in a||(a.base='string'==typeof e?e:''),'documentLoader'in a||(a.documentLoader=t.loadDocument),t.expand(e,a,function(e,o){if(e)return r(new De('Could not expand input before linking.','jsonld.LinkError',{cause:e}));var i;try{i=new Ue().flatten(o)}catch(e){return r(e)}a.graph=!0,a.skipExpansion=!0,t.compact(i,n,a,function(e,n,a){if(e)return r(new De('Could not compact flattened output before linking.','jsonld.LinkError',{cause:e}));var o=O(a,'@graph'),d=n[o][0],l=function(e){if(B(e)||H(e)){if(B(e)){if(l.visited[e['@id']])return;l.visited[e['@id']]=!0}for(var n in e){var r=e[n],o='@id'===t.getContextValue(a,n,'@type');if(H(r)||B(r)||o)if(V(r)&&o)e[n]=r=d[r],l(r);else if(H(r))for(var s=0;sarguments.length)return t.nextTick(function(){a(new TypeError('Could not normalize, too few arguments.'))});if('function'==typeof n&&(a=n,n={}),n=n||{},'algorithm'in n||(n.algorithm='URGNA2012'),'base'in n||(n.base='string'==typeof e?e:''),'documentLoader'in n||(n.documentLoader=t.loadDocument),'inputFormat'in n){if('application/nquads'!==n.inputFormat)return a(new De('Unknown normalization input format.','jsonld.NormalizeError'));var r=ie(e);new Ue().normalize(r,n,a)}else{var o=ae(n);delete o.format,o.produceGeneralizedRdf=!1,t.toRDF(e,o,function(e,t){return e?a(new De('Could not convert input to RDF dataset before normalization.','jsonld.NormalizeError',{cause:e})):void new Ue().normalize(t,n,a)})}},t.fromRDF=function(e,n,a){return 1>arguments.length?t.nextTick(function(){a(new TypeError('Could not convert from RDF, too few arguments.'))}):void('function'==typeof n&&(a=n,n={}),n=n||{},!('useRdfType'in n)&&(n.useRdfType=!1),!('useNativeTypes'in n)&&(n.useNativeTypes=!1),!('format'in n)&&V(e)&&!('format'in n)&&(n.format='application/nquads'),t.nextTick(function(){function t(e,t,n){new Ue().fromRDF(e,t,n)}var r;if(!n.format)r=function(){return e};else if(r=n.rdfParser||ge[n.format],!r)return a(new De('Unknown input format.','jsonld.UnknownFormat',{format:n.format}));var o=!1;try{e=r(e,function(e,r){return o=!0,e?a(e):void t(r,n,a)})}catch(t){if(!o)return a(t);throw t}if(e){if('then'in e)return e.then(function(e){t(e,n,a)},a);t(e,n,a)}}))},t.toRDF=function(e,n,a){return 1>arguments.length?t.nextTick(function(){a(new TypeError('Could not convert to RDF, too few arguments.'))}):void('function'==typeof n&&(a=n,n={}),n=n||{},!('base'in n)&&(n.base='string'==typeof e?e:''),!('documentLoader'in n)&&(n.documentLoader=t.loadDocument),t.expand(e,n,function(e,t){if(e)return a(new De('Could not expand input before serialization to RDF.','jsonld.RdfError',{cause:e}));var r;try{if(r=Ue.prototype.toRDF(t,n),n.format){if('application/nquads'===n.format)return a(null,se(r));throw new De('Unknown output format.','jsonld.UnknownFormat',{format:n.format})}}catch(e){return a(e)}a(null,r)}))},t.createNodeMap=function(e,n,a){return 1>arguments.length?t.nextTick(function(){a(new TypeError('Could not create node map, too few arguments.'))}):void('function'==typeof n&&(a=n,n={}),n=n||{},!('base'in n)&&(n.base='string'==typeof e?e:''),!('documentLoader'in n)&&(n.documentLoader=t.loadDocument),t.expand(e,n,function(e,t){if(e)return a(new De('Could not expand input before creating node map.','jsonld.CreateNodeMapError',{cause:e}));var r;try{r=new Ue().createNodeMap(t,n)}catch(e){return a(e)}a(null,r)}))},t.merge=function(e,n,a,r){function o(e,t){return l?void 0:e?(l=e,r(new De('Could not expand input before flattening.','jsonld.FlattenError',{cause:e}))):void(d.push(t),0==--p&&s(d))}function s(e){var o=!0;'mergeNodes'in a&&(o=a.mergeNodes);var s=a.namer||a.issuer||new pe('_:b'),d={"@default":{}},l;try{for(var p=0,i;parguments.length)return t.nextTick(function(){r(new TypeError('Could not merge, too few arguments.'))});if(!H(e))return t.nextTick(function(){r(new TypeError('Could not merge, "docs" must be an array.'))});'function'==typeof a?(r=a,a={}):'function'==typeof n&&(r=n,n=null,a={}),a=a||{};for(var d=[],l=null,p=e.length,u=0,i;uarguments.length)throw new TypeError('Could not expand, too few arguments.');return r.apply(null,[t.expand].concat(a.call(arguments)))},i.compact=function(e,n){if(2>arguments.length)throw new TypeError('Could not compact, too few arguments.');var o=function(e,n,a,r){'function'==typeof a&&(r=a,a={}),a=a||{},t.compact(e,n,a,function(e,t){r(e,t)})};return r.apply(null,[o].concat(a.call(arguments)))},i.flatten=function(e){if(1>arguments.length)throw new TypeError('Could not flatten, too few arguments.');return r.apply(null,[t.flatten].concat(a.call(arguments)))},i.frame=function(e,n){if(2>arguments.length)throw new TypeError('Could not frame, too few arguments.');return r.apply(null,[t.frame].concat(a.call(arguments)))},i.fromRDF=function(e){if(1>arguments.length)throw new TypeError('Could not convert from RDF, too few arguments.');return r.apply(null,[t.fromRDF].concat(a.call(arguments)))},i.toRDF=function(e){if(1>arguments.length)throw new TypeError('Could not convert to RDF, too few arguments.');return r.apply(null,[t.toRDF].concat(a.call(arguments)))},i.normalize=function(e){if(1>arguments.length)throw new TypeError('Could not normalize, too few arguments.');return r.apply(null,[t.normalize].concat(a.call(arguments)))},'jsonld.js'===s&&(i.link=function(e,n){if(2>arguments.length)throw new TypeError('Could not link, too few arguments.');return r.apply(null,[t.link].concat(a.call(arguments)))},i.objectify=function(e){return r.apply(null,[t.objectify].concat(a.call(arguments)))},i.createNodeMap=function(e){return r.apply(null,[t.createNodeMap].concat(a.call(arguments)))},i.merge=function(e){return r.apply(null,[t.merge].concat(a.call(arguments)))});try{t.Promise=o.Promise||n(40).Promise}catch(t){var d=function(){throw new Error('Unable to find a Promise implementation.')};for(var l in i)i[l]=d}return i},t.promisify=function(e){if(!t.Promise)try{t.Promise=o.Promise||n(40).Promise}catch(t){throw new Error('Unable to find a Promise implementation.')}var a=Array.prototype.slice.call(arguments,1);return new t.Promise(function(t,n){e.apply(null,a.concat(function(e,a){e?n(e):t(a)}))})},t.promises({api:t.promises}),e.prototype=t.promises({version:'json-ld-1.0'}),e.prototype.toString=function(){return this instanceof e?'[object JsonLdProcessor]':'[object JsonLdProcessorPrototype]'},t.JsonLdProcessor=e;var ce=!!Object.defineProperty;if(ce)try{Object.defineProperty({},'x',{})}catch(t){ce=!1}ce&&(Object.defineProperty(e,'prototype',{writable:!1,enumerable:!1}),Object.defineProperty(e.prototype,'constructor',{writable:!0,enumerable:!1,configurable:!0,value:e})),u&&'undefined'==typeof o.JsonLdProcessor&&(ce?Object.defineProperty(o,'JsonLdProcessor',{writable:!0,enumerable:!1,configurable:!0,value:e}):o.JsonLdProcessor=e);var he='function'==typeof i&&i,fe=he?function(e){he(e)}:function(e){setTimeout(e,0)};t.nextTick='object'==typeof a&&'function'==typeof a.nextTick?a.nextTick:fe,t.setImmediate=he?fe:t.nextTick,t.parseLinkHeader=function(e){for(var t={},n=e.match(/(?:<[^>]*?>|"[^"]*?"|[^,])+/g),a=/\s*<([^>]*?)>\s*(?:;\s*(.*))?/,r=0,o;r=+new Date)return t.ctx;delete this.cache[e],this.order.splice(this.order.indexOf(e),1)}return null},t.DocumentCache.prototype.set=function(e,t){this.order.length===this.size&&delete this.cache[this.order.shift()],this.order.push(e),this.cache[e]={ctx:t,expires:+new Date+this.expires}},t.ActiveContextCache=function(e){this.order=[],this.cache={},this.size=e||100},t.ActiveContextCache.prototype.get=function(e,t){var n=JSON.stringify(e),a=JSON.stringify(t),r=this.cache[n];return r&&a in r?r[a]:null},t.ActiveContextCache.prototype.set=function(e,t,n){if(this.order.length===this.size){var a=this.order.shift();delete this.cache[a.activeCtx][a.localCtx]}var r=JSON.stringify(e),o=JSON.stringify(t);this.order.push({activeCtx:r,localCtx:o}),r in this.cache||(this.cache[r]={}),this.cache[r][o]=ae(n)},t.cache={activeCtx:new t.ActiveContextCache},t.documentLoaders={},t.documentLoaders.jquery=function(e,n){function a(a,r){return 0!==a.indexOf('http:')&&0!==a.indexOf('https:')?r(new De('URL could not be dereferenced; only "http" and "https" URLs are supported.','jsonld.InvalidUrl',{code:'loading document failed',url:a}),{contextUrl:null,documentUrl:a,document:null}):n.secure&&0!==a.indexOf('https')?r(new De('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".','jsonld.InvalidUrl',{code:'loading document failed',url:a}),{contextUrl:null,documentUrl:a,document:null}):void e.ajax({url:a,accepts:{json:'application/ld+json, application/json'},headers:{Accept:'application/ld+json, application/json'},dataType:'json',crossDomain:!0,success:function(e,n,o){var i={contextUrl:null,documentUrl:a,document:e},s=o.getResponseHeader('Content-Type'),d=o.getResponseHeader('Link');if(d&&'application/ld+json'!==s){if(d=t.parseLinkHeader(d)[Oe],H(d))return r(new De('URL could not be dereferenced, it has more than one associated HTTP Link Header.','jsonld.InvalidUrl',{code:'multiple context link headers',url:a}),i);d&&(i.contextUrl=d.target)}r(null,i)},error:function(e,t,n){r(new De('URL could not be dereferenced, an error occurred.','jsonld.LoadDocumentError',{code:'loading document failed',url:a,cause:n}),{contextUrl:null,documentUrl:a,document:null})}})}n=n||{};var r=new t.RequestQueue,o='usePromise'in n?n.usePromise:'undefined'!=typeof Promise;return o?r.wrapLoader(function(e){return t.promisify(a,e)}):r.wrapLoader(a)},t.documentLoaders.node=function(e){function a(n,l,p){function u(e,r,i){if(c={contextUrl:null,documentUrl:n,document:i||null},e)return p(new De('URL could not be dereferenced, an error occurred.','jsonld.LoadDocumentError',{code:'loading document failed',url:n,cause:e}),c);var s=d.STATUS_CODES[r.statusCode];if(400<=r.statusCode)return p(new De('URL could not be dereferenced: '+s,'jsonld.InvalidUrl',{code:'loading document failed',url:n,httpStatusCode:r.statusCode}),c);if(r.headers.link&&'application/ld+json'!==r.headers['content-type']){var u=t.parseLinkHeader(r.headers.link)[Oe];if(H(u))return p(new De('URL could not be dereferenced, it has more than one associated HTTP Link Header.','jsonld.InvalidUrl',{code:'multiple context link headers',url:n}),c);u&&(c.contextUrl=u.target)}return 300<=r.statusCode&&400>r.statusCode&&r.headers.location?l.length===o?p(new De('URL could not be dereferenced; there were too many redirects.','jsonld.TooManyRedirects',{code:'loading document failed',url:n,httpStatusCode:r.statusCode,redirects:l}),c):-1===l.indexOf(n)?(l.push(n),a(r.headers.location,l,p)):p(new De('URL could not be dereferenced; infinite redirection was detected.','jsonld.InfiniteRedirectDetected',{code:'recursive context inclusion',url:n,httpStatusCode:r.statusCode,redirects:l}),c):void(l.push(n),p(e,c))}if(0!==n.indexOf('http:')&&0!==n.indexOf('https:'))return p(new De('URL could not be dereferenced; only "http" and "https" URLs are supported.','jsonld.InvalidUrl',{code:'loading document failed',url:n}),{contextUrl:null,documentUrl:n,document:null});if(e.secure&&0!==n.indexOf('https'))return p(new De('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".','jsonld.InvalidUrl',{code:'loading document failed',url:n}),{contextUrl:null,documentUrl:n,document:null});var c=null;if(null!==c)return p(null,c);var h={Accept:s};for(var f in e.headers)h[f]=e.headers[f];i({url:n,headers:h,strictSSL:r,followRedirect:!1},u)}e=e||{};var r=!('strictSSL'in e)||e.strictSSL,o='maxRedirects'in e?e.maxRedirects:-1,i='request'in e?e.request:n(12),s='application/ld+json, application/json',d=n(12),l=new t.RequestQueue;if(e.usePromise)return l.wrapLoader(function(e){return t.promisify(a,e,[])});var p=e.headers||{};if('Accept'in p||'accept'in p)throw new RangeError('Accept header may not be specified as an option; only "'+s+'" is supported.');return l.wrapLoader(function(e,t){a(e,[],t)})},t.documentLoaders.xhr=function(e){function n(n,r){if(0!==n.indexOf('http:')&&0!==n.indexOf('https:'))return r(new De('URL could not be dereferenced; only "http" and "https" URLs are supported.','jsonld.InvalidUrl',{code:'loading document failed',url:n}),{contextUrl:null,documentUrl:n,document:null});if(e.secure&&0!==n.indexOf('https'))return r(new De('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".','jsonld.InvalidUrl',{code:'loading document failed',url:n}),{contextUrl:null,documentUrl:n,document:null});var o=e.xhr||XMLHttpRequest,i=new o;i.onload=function(){if(400<=i.status)return r(new De('URL could not be dereferenced: '+i.statusText,'jsonld.LoadDocumentError',{code:'loading document failed',url:n,httpStatusCode:i.status}),{contextUrl:null,documentUrl:n,document:null});var e={contextUrl:null,documentUrl:n,document:i.response},o=i.getResponseHeader('Content-Type'),s;if(a.test(i.getAllResponseHeaders())&&(s=i.getResponseHeader('Link')),s&&'application/ld+json'!==o){if(s=t.parseLinkHeader(s)[Oe],H(s))return r(new De('URL could not be dereferenced, it has more than one associated HTTP Link Header.','jsonld.InvalidUrl',{code:'multiple context link headers',url:n}),e);s&&(e.contextUrl=s.target)}r(null,e)},i.onerror=function(){r(new De('URL could not be dereferenced, an error occurred.','jsonld.LoadDocumentError',{code:'loading document failed',url:n}),{contextUrl:null,documentUrl:n,document:null})},i.open('GET',n,!0),i.setRequestHeader('Accept','application/ld+json, application/json'),i.send()}e=e||{};var a=/(^|(\r\n))link:/i,r=new t.RequestQueue,o='usePromise'in e?e.usePromise:'undefined'!=typeof Promise;return o?r.wrapLoader(function(e){return t.promisify(n,e)}):r.wrapLoader(n)},t.useDocumentLoader=function(e){if(!(e in t.documentLoaders))throw new De('Unknown document loader type: "'+e+'"','jsonld.UnknownDocumentLoader',{type:e});t.documentLoader=t.documentLoaders[e].apply(t,Array.prototype.slice.call(arguments,1))},t.processContext=function(e,n){var a={},r=2;3=a.MAX_TOTAL_DEPTH?n(new Error('Maximum total call stack depth exceeded; normalization aborting.')):void function r(){if(a.depth===a.MAX_DEPTH)return a.depth=0,a.running=!1,t.nextTick(r);var o=new Date().getTime();return a.running||(a.start=new Date().getTime(),a.deadline=a.start+a.timeSlice),ot.hash?1:0}),n.forEach(r,function(e,t,a){for(var r in e.issuer.existing)n.canonicalIssuer.getId(r);a()},e)}],a)},e)},function(e){var t=[];n.waterfall([function(e){n.forEach(n.quads,function(e,a,r){n.forEachComponent(e,function(e){'blank node'===e.type&&0!==e.value.indexOf(n.canonicalIssuer.prefix)&&(e.value=n.canonicalIssuer.getId(e.value))}),t.push(de(e)),r()},e)},function(e){return t.sort(),'application/nquads'===n.options.format?(a=t.join(''),e()):void(a=ie(t.join('')),e())}],e)}],function(e){t(e,a)})},n.prototype.hashFirstDegreeQuads=function(e,t){var n=this,a=n.blankNodeInfo[e];if('hash'in a)return t(null,a.hash);var r=[],o=a.quads;n.forEach(o,function(t,a,o){var i={predicate:t.predicate};n.forEachComponent(t,function(t,a){i[a]=n.modifyFirstDegreeComponent(e,t,a)}),r.push(de(i)),o()},function(e){return e?t(e):void(r.sort(),a.hash=Fe.hashNQuads(n.name,r),t(null,a.hash))})},n.prototype.modifyFirstDegreeComponent=function(e,t){return'blank node'===t.type?(t=ae(t),t.value=t.value===e?'_:a':'_:z',t):t},n.prototype.hashRelatedBlankNode=function(e,t,n,a,r){var o=this,i;o.waterfall([function(t){return o.canonicalIssuer.hasId(e)?(i=o.canonicalIssuer.getId(e),t()):n.hasId(e)?(i=n.getId(e),t()):void o.hashFirstDegreeQuads(e,function(e,n){return e?t(e):void(i=n,t())})}],function(e){if(e)return r(e);var n=new Fe(o.name);return n.update(a),'g'!==a&&n.update(o.getRelatedPredicate(t)),n.update(i),r(null,n.digest())})},n.prototype.getRelatedPredicate=function(e){return'<'+e.predicate.value+'>'},n.prototype.hashNDegreeQuads=function(e,t,n){var a=this,r=new Fe(a.name),o;a.waterfall([function(n){a.createHashToRelated(e,t,function(e,t){return e?n(e):void(o=t,n())})},function(e){var n=Object.keys(o).sort();a.forEach(n,function(e,n,i){r.update(e);var s='',d=new Me(o[e]),l;a.whilst(function(){return d.hasNext()},function(e){var n=d.next(),r=t.clone(),o='',i=[];a.waterfall([function(t){a.forEach(n,function(t,n,d){return a.canonicalIssuer.hasId(t)?o+=a.canonicalIssuer.getId(t):(!r.hasId(t)&&i.push(t),o+=r.getId(t)),0!==s.length&&o.length>=s.length&&o>s?e():void d()},t)},function(t){a.forEach(i,function(t,n,i){a.hashNDegreeQuads(t,r,function(n,a){return n?i(n):(o+=r.getId(t),o+='<'+a.hash+'>',r=a.issuer,0!==s.length&&o.length>=s.length&&o>s?e():void i())})},t)},function(e){(0===s.length||ot)&&(i&&0this.list[r-1]||!i&&rthis.list[r+1])&&(t=o,n=r)}if(null===t)this.done=!0;else{var s=this.left[t]?n-1:n+1;this.list[n]=this.list[s],this.list[s]=t;for(var r=0;rt&&(this.left[this.list[r]]=!this.left[this.list[r]])}return e};var Fe=function(e){if(!(this instanceof Fe))return new Fe(e);if(-1===['URDNA2015','URGNA2012'].indexOf(e))throw new Error('Invalid RDF Dataset Normalization algorithm: '+e);Fe._init.call(this,e)};if(Fe.hashNQuads=function(e,t){for(var n=new Fe(e),a=0;a>>=1,0>>0,t>>>0];for(var n=this.fullMessageLength.length-1;0<=n;--n)this.fullMessageLength[n]+=t[1],t[1]=t[0]+(this.fullMessageLength[n]/4294967296>>>0),this.fullMessageLength[n]>>>=0,t[0]=t[1]/4294967296>>>0;for(this._input.putBytes(e.bytes());this._input.length()>=this._algorithm.blockSize;)this.state=this._algorithm.digest(this.state,this._input);return(2048>>28);this._algorithm.writeMessageLength(e,r);var i=this._algorithm.digest(this.state.copy(),e),s=new a.ByteBuffer;return i.write(s),s},a.ByteBuffer=function(e){this.data='string'==typeof e?e:'',this.read=0},a.ByteBuffer.prototype.putInt32=function(e){this.data+=r(255&e>>24)+r(255&e>>16)+r(255&e>>8)+r(255&e)},a.ByteBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},a.ByteBuffer.prototype.putBytes=function(e){this.data+=e},a.ByteBuffer.prototype.bytes=function(){return this.data.slice(this.read)},a.ByteBuffer.prototype.length=function(){return this.data.length-this.read},a.ByteBuffer.prototype.compact=function(){this.data=this.data.slice(this.read),this.read=0},a.ByteBuffer.prototype.toHex=function(){for(var e='',t=this.read,n;tn&&(e+='0'),e+=n.toString(16);return e};var o={_w:null};o.Algorithm=function(){this.name='sha1',this.blockSize=64,this.digestLength=20,this.messageLengthSize=8},o.Algorithm.prototype.start=function(){return o._w||(o._w=Array(80)),o._createState()},o.Algorithm.prototype.writeMessageLength=function(e,t){e.putBytes(t.bytes())},o.Algorithm.prototype.digest=function(n,r){for(var s=r.length(),l=o._w,p,t,a,u,c,d,e,h;64<=s;){for(t=n.h0,a=n.h1,u=n.h2,c=n.h3,d=n.h4,h=0;16>h;++h)p=r.getInt32(),l[h]=p,e=c^a&(u^c),p=(t<<5|t>>>27)+e+d+1518500249+p,d=c,c=u,u=a<<30|a>>>2,a=t,t=p;for(;20>h;++h)p=l[h-3]^l[h-8]^l[h-14]^l[h-16],p=p<<1|p>>>31,l[h]=p,e=c^a&(u^c),p=(t<<5|t>>>27)+e+d+1518500249+p,d=c,c=u,u=a<<30|a>>>2,a=t,t=p;for(;32>h;++h)p=l[h-3]^l[h-8]^l[h-14]^l[h-16],p=p<<1|p>>>31,l[h]=p,e=a^u^c,p=(t<<5|t>>>27)+e+d+1859775393+p,d=c,c=u,u=a<<30|a>>>2,a=t,t=p;for(;40>h;++h)p=l[h-6]^l[h-16]^l[h-28]^l[h-32],p=p<<2|p>>>30,l[h]=p,e=a^u^c,p=(t<<5|t>>>27)+e+d+1859775393+p,d=c,c=u,u=a<<30|a>>>2,a=t,t=p;for(;60>h;++h)p=l[h-6]^l[h-16]^l[h-28]^l[h-32],p=p<<2|p>>>30,l[h]=p,e=a&u|c&(a^u),p=(t<<5|t>>>27)+e+d+2400959708+p,d=c,c=u,u=a<<30|a>>>2,a=t,t=p;for(;80>h;++h)p=l[h-6]^l[h-16]^l[h-28]^l[h-32],p=p<<2|p>>>30,l[h]=p,e=a^u^c,p=(t<<5|t>>>27)+e+d+3395469782+p,d=c,c=u,u=a<<30|a>>>2,a=t,t=p;n.h0=0|n.h0+t,n.h1=0|n.h1+a,n.h2=0|n.h2+u,n.h3=0|n.h3+c,n.h4=0|n.h4+d,s-=64}return n},o._createState=function(){var e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520};return e.copy=function(){var t=o._createState();return t.h0=e.h0,t.h1=e.h1,t.h2=e.h2,t.h3=e.h3,t.h4=e.h4,t},e.write=function(t){t.putInt32(e.h0),t.putInt32(e.h1),t.putInt32(e.h2),t.putInt32(e.h3),t.putInt32(e.h4)},e};var l={_k:null,_w:null};l.Algorithm=function(){this.name='sha256',this.blockSize=64,this.digestLength=32,this.messageLengthSize=8},l.Algorithm.prototype.start=function(){return l._k||l._init(),l._createState()},l.Algorithm.prototype.writeMessageLength=function(e,t){e.putBytes(t.bytes())},l.Algorithm.prototype.digest=function(t,n){for(var r=n.length(),o=l._k,s=l._w,p,u,m,y,x,_,v,i,a,b,c,d,e,f,g;64<=r;){for(v=0;16>v;++v)s[v]=n.getInt32();for(;64>v;++v)p=s[v-2],p=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,u=s[v-15],u=(u>>>7|u<<25)^(u>>>18|u<<14)^u>>>3,s[v]=0|p+s[v-7]+u+s[v-16];for(i=t.h0,a=t.h1,b=t.h2,c=t.h3,d=t.h4,e=t.h5,f=t.h6,g=t.h7,v=0;64>v;++v)y=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),x=f^d&(e^f),m=(i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10),_=i&a|b&(i^a),p=g+y+x+o[v]+s[v],u=m+_,g=f,f=e,e=d,d=0|c+p,c=b,b=a,a=i,i=0|p+u;t.h0=0|t.h0+i,t.h1=0|t.h1+a,t.h2=0|t.h2+b,t.h3=0|t.h3+c,t.h4=0|t.h4+d,t.h5=0|t.h5+e,t.h6=0|t.h6+f,t.h7=0|t.h7+g,r-=64}return t},l._createState=function(){var e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225};return e.copy=function(){var t=l._createState();return t.h0=e.h0,t.h1=e.h1,t.h2=e.h2,t.h3=e.h3,t.h4=e.h4,t.h5=e.h5,t.h6=e.h6,t.h7=e.h7,t},e.write=function(t){t.putInt32(e.h0),t.putInt32(e.h1),t.putInt32(e.h2),t.putInt32(e.h3),t.putInt32(e.h4),t.putInt32(e.h5),t.putInt32(e.h6),t.putInt32(e.h7)},e},l._init=function(){l._k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],l._w=Array(64)}}(p),!me)var Be=function(){me=n(41).XMLSerializer};if(t.url={},t.url.parsers={simple:{keys:['href','scheme','authority','path','query','fragment'],regex:/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/},full:{keys:['href','protocol','scheme','authority','auth','user','password','hostname','port','path','directory','file','query','fragment'],regex:/^(([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/}},t.url.parse=function(e,n){for(var a={},r=t.url.parsers[n||'full'],o=r.regex.exec(e),s=r.keys.length;s--;)a[r.keys[s]]=void 0===o[s]?null:o[s];return a.normalizedPath=ue(a.path,!!a.authority),a},p?t.useDocumentLoader('node'):'undefined'!=typeof XMLHttpRequest&&t.useDocumentLoader('xhr'),p){t.use=function(e){switch(e){case'request':t.request=n(12);break;default:throw new De('Unknown extension.','jsonld.UnknownExtension',{extension:e});}};var qe={exports:{},filename:s};n(12)(qe,'version'),t.version=qe.exports.version}return t},h=function(){return c(function(){return h()})};return!p&&n(64)?(d=[],l=function(){return c(h),h}.apply(t,d),!(void 0!==l&&(e.exports=l))):(c(h),'undefined'!=typeof e&&e.exports&&(e.exports=h),u&&('undefined'==typeof jsonld?jsonld=jsonldjs=h:jsonldjs=h)),h})()}).call(this,n(5),n(3),n(13).setImmediate,'/')},function(e,t,n){(function(a,r,o){var i,s;/*! + */ +function t(n,r,i){if(re(r)){for(var o=[],a=0;a0&&"/"!==o.substr(-1)&&(o+="/"),o+=r.path),i.path=o}i.query=r.query}i.path=Te(i.path,!!i.authority);var a=i.protocol;null!==i.authority&&(a+="//"+i.authority);a+=i.path,null!==i.query&&(a+="?"+i.query);null!==r.fragment&&(a+="#"+r.fragment);""===a&&(a="./");return a}(t,n)},e.documentLoader=function(t,n){var r=new I("Could not retrieve a JSON-LD document from the URL. URL dereferencing not implemented.","jsonld.LoadDocumentError",{code:"loading document failed"});return u?n(r,{contextUrl:null,documentUrl:t,document:null}):e.promisify(function(e){e(r)})},e.loadDocument=function(t,n){var r=e.documentLoader(t,n);r&&"then"in r&&r.then(n.bind(null,null),n)},e.promises=function(t){t=t||{};var r=Array.prototype.slice,o=e.promisify,a=t.api||{},s=t.version||"jsonld.js";"string"==typeof t.api&&(t.version||(s=t.api),a={}),a.expand=function(t){if(arguments.length<1)throw new TypeError("Could not expand, too few arguments.");return o.apply(null,[e.expand].concat(r.call(arguments)))},a.compact=function(t,n){if(arguments.length<2)throw new TypeError("Could not compact, too few arguments.");return o.apply(null,[function(t,n,r,i){"function"==typeof r&&(i=r,r={}),r=r||{},e.compact(t,n,r,function(e,t){i(e,t)})}].concat(r.call(arguments)))},a.flatten=function(t){if(arguments.length<1)throw new TypeError("Could not flatten, too few arguments.");return o.apply(null,[e.flatten].concat(r.call(arguments)))},a.frame=function(t,n){if(arguments.length<2)throw new TypeError("Could not frame, too few arguments.");return o.apply(null,[e.frame].concat(r.call(arguments)))},a.fromRDF=function(t){if(arguments.length<1)throw new TypeError("Could not convert from RDF, too few arguments.");return o.apply(null,[e.fromRDF].concat(r.call(arguments)))},a.toRDF=function(t){if(arguments.length<1)throw new TypeError("Could not convert to RDF, too few arguments.");return o.apply(null,[e.toRDF].concat(r.call(arguments)))},a.normalize=function(t){if(arguments.length<1)throw new TypeError("Could not normalize, too few arguments.");return o.apply(null,[e.normalize].concat(r.call(arguments)))},"jsonld.js"===s&&(a.link=function(t,n){if(arguments.length<2)throw new TypeError("Could not link, too few arguments.");return o.apply(null,[e.link].concat(r.call(arguments)))},a.objectify=function(t){return o.apply(null,[e.objectify].concat(r.call(arguments)))},a.createNodeMap=function(t){return o.apply(null,[e.createNodeMap].concat(r.call(arguments)))},a.merge=function(t){return o.apply(null,[e.merge].concat(r.call(arguments)))});try{e.Promise=i.Promise||n(40).Promise}catch(e){var u=function(){throw new Error("Unable to find a Promise implementation.")};for(var l in a)a[l]=u}return a},e.promisify=function(t){if(!e.Promise)try{e.Promise=i.Promise||n(40).Promise}catch(e){throw new Error("Unable to find a Promise implementation.")}var r=Array.prototype.slice.call(arguments,1);return new e.Promise(function(e,n){t.apply(null,r.concat(function(t,r){t?n(t):e(r)}))})},e.promises({api:e.promises}),t.prototype=e.promises({version:"json-ld-1.0"}),t.prototype.toString=function(){return this instanceof t?"[object JsonLdProcessor]":"[object JsonLdProcessorPrototype]"},e.JsonLdProcessor=t;var s=!!Object.defineProperty;if(s)try{Object.defineProperty({},"x",{})}catch(e){s=!1}s&&(Object.defineProperty(t,"prototype",{writable:!1,enumerable:!1}),Object.defineProperty(t.prototype,"constructor",{writable:!0,enumerable:!1,configurable:!0,value:t})),l&&void 0===i.JsonLdProcessor&&(s?Object.defineProperty(i,"JsonLdProcessor",{writable:!0,enumerable:!1,configurable:!0,value:t}):i.JsonLdProcessor=t);var c="function"==typeof o&&o,f=c?function(e){c(e)}:function(e){setTimeout(e,0)};"object"==typeof r&&"function"==typeof r.nextTick?e.nextTick=r.nextTick:e.nextTick=f,e.setImmediate=c?f:e.nextTick,e.parseLinkHeader=function(e){for(var t={},n=e.match(/(?:<[^>]*?>|"[^"]*?"|[^,])+/g),r=/\s*<([^>]*?)>\s*(?:;\s*(.*))?/,i=0;i=+new Date)return t.ctx;delete this.cache[e],this.order.splice(this.order.indexOf(e),1)}return null},e.DocumentCache.prototype.set=function(e,t){this.order.length===this.size&&delete this.cache[this.order.shift()],this.order.push(e),this.cache[e]={ctx:t,expires:+new Date+this.expires}},e.ActiveContextCache=function(e){this.order=[],this.cache={},this.size=e||100},e.ActiveContextCache.prototype.get=function(e,t){var n=JSON.stringify(e),r=JSON.stringify(t),i=this.cache[n];return i&&r in i?i[r]:null},e.ActiveContextCache.prototype.set=function(e,t,n){if(this.order.length===this.size){var r=this.order.shift();delete this.cache[r.activeCtx][r.localCtx]}var i=JSON.stringify(e),o=JSON.stringify(t);this.order.push({activeCtx:i,localCtx:o}),i in this.cache||(this.cache[i]={}),this.cache[i][o]=ve(n)},e.cache={activeCtx:new e.ActiveContextCache},e.documentLoaders={},e.documentLoaders.jquery=function(t,n){n=n||{};var r=new e.RequestQueue;return("usePromise"in n?n.usePromise:"undefined"!=typeof Promise)?r.wrapLoader(function(t){return e.promisify(i,t)}):r.wrapLoader(i);function i(r,i){return 0!==r.indexOf("http:")&&0!==r.indexOf("https:")?i(new I('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:r}),{contextUrl:null,documentUrl:r,document:null}):n.secure&&0!==r.indexOf("https")?i(new I('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".',"jsonld.InvalidUrl",{code:"loading document failed",url:r}),{contextUrl:null,documentUrl:r,document:null}):void t.ajax({url:r,accepts:{json:"application/ld+json, application/json"},headers:{Accept:"application/ld+json, application/json"},dataType:"json",crossDomain:!0,success:function(t,n,o){var a={contextUrl:null,documentUrl:r,document:t},s=o.getResponseHeader("Content-Type"),u=o.getResponseHeader("Link");if(u&&"application/ld+json"!==s){if(re(u=e.parseLinkHeader(u)[O]))return i(new I("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:r}),a);u&&(a.contextUrl=u.target)}i(null,a)},error:function(e,t,n){i(new I("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:r,cause:n}),{contextUrl:null,documentUrl:r,document:null})}})}},e.documentLoaders.node=function(t){var r=!("strictSSL"in(t=t||{}))||t.strictSSL,i="maxRedirects"in t?t.maxRedirects:-1,o="request"in t?t.request:n(13),a="application/ld+json, application/json",s=n(13),u=new e.RequestQueue;if(t.usePromise)return u.wrapLoader(function(t){return e.promisify(c,t,[])});var l=t.headers||{};if("Accept"in l||"accept"in l)throw new RangeError('Accept header may not be specified as an option; only "'+a+'" is supported.');return u.wrapLoader(function(e,t){c(e,[],t)});function c(n,u,l){if(0!==n.indexOf("http:")&&0!==n.indexOf("https:"))return l(new I('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:n}),{contextUrl:null,documentUrl:n,document:null});if(t.secure&&0!==n.indexOf("https"))return l(new I('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".',"jsonld.InvalidUrl",{code:"loading document failed",url:n}),{contextUrl:null,documentUrl:n,document:null});var f=null;if(null!==f)return l(null,f);var h={Accept:a};for(var d in t.headers)h[d]=t.headers[d];o({url:n,headers:h,strictSSL:r,followRedirect:!1},function(t,r,o){if(f={contextUrl:null,documentUrl:n,document:o||null},t)return l(new I("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:n,cause:t}),f);var a=s.STATUS_CODES[r.statusCode];if(r.statusCode>=400)return l(new I("URL could not be dereferenced: "+a,"jsonld.InvalidUrl",{code:"loading document failed",url:n,httpStatusCode:r.statusCode}),f);if(r.headers.link&&"application/ld+json"!==r.headers["content-type"]){var h=e.parseLinkHeader(r.headers.link)[O];if(re(h))return l(new I("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:n}),f);h&&(f.contextUrl=h.target)}if(r.statusCode>=300&&r.statusCode<400&&r.headers.location)return u.length===i?l(new I("URL could not be dereferenced; there were too many redirects.","jsonld.TooManyRedirects",{code:"loading document failed",url:n,httpStatusCode:r.statusCode,redirects:u}),f):-1!==u.indexOf(n)?l(new I("URL could not be dereferenced; infinite redirection was detected.","jsonld.InfiniteRedirectDetected",{code:"recursive context inclusion",url:n,httpStatusCode:r.statusCode,redirects:u}),f):(u.push(n),c(r.headers.location,u,l));u.push(n),l(t,f)})}},e.documentLoaders.xhr=function(t){t=t||{};var n=/(^|(\r\n))link:/i,r=new e.RequestQueue;return("usePromise"in t?t.usePromise:"undefined"!=typeof Promise)?r.wrapLoader(function(t){return e.promisify(i,t)}):r.wrapLoader(i);function i(r,i){if(0!==r.indexOf("http:")&&0!==r.indexOf("https:"))return i(new I('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:r}),{contextUrl:null,documentUrl:r,document:null});if(t.secure&&0!==r.indexOf("https"))return i(new I('URL could not be dereferenced; secure mode is enabled and the URL\'s scheme is not "https".',"jsonld.InvalidUrl",{code:"loading document failed",url:r}),{contextUrl:null,documentUrl:r,document:null});var o=new(t.xhr||XMLHttpRequest);o.onload=function(){if(o.status>=400)return i(new I("URL could not be dereferenced: "+o.statusText,"jsonld.LoadDocumentError",{code:"loading document failed",url:r,httpStatusCode:o.status}),{contextUrl:null,documentUrl:r,document:null});var t,a={contextUrl:null,documentUrl:r,document:o.response},s=o.getResponseHeader("Content-Type");if(n.test(o.getAllResponseHeaders())&&(t=o.getResponseHeader("Link")),t&&"application/ld+json"!==s){if(re(t=e.parseLinkHeader(t)[O]))return i(new I("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:r}),a);t&&(a.contextUrl=t.target)}i(null,a)},o.onerror=function(){i(new I("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:r}),{contextUrl:null,documentUrl:r,document:null})},o.open("GET",r,!0),o.setRequestHeader("Accept","application/ld+json, application/json"),o.send()}},e.useDocumentLoader=function(t){if(!(t in e.documentLoaders))throw new I('Unknown document loader type: "'+t+'"',"jsonld.UnknownDocumentLoader",{type:t});e.documentLoader=e.documentLoaders[t].apply(e,Array.prototype.slice.call(arguments,1))},e.processContext=function(t,n){var r={},i=2;arguments.length>3&&(r=arguments[2]||{},i+=1);var o=arguments[i];if("base"in r||(r.base=""),"documentLoader"in r||(r.documentLoader=e.loadDocument),null===n)return o(null,ee(r));ne(n=ve(n))&&"@context"in n||(n={"@context":n}),ge(n,r,function(e,n){if(e)return o(e);try{n=(new R).processContext(t,n,r)}catch(e){return o(e)}o(null,n)})},e.hasProperty=function(e,t){var n=!1;if(t in e){var r=e[t];n=!re(r)||r.length>0}return n},e.hasValue=function(t,n,r){var i=!1;if(e.hasProperty(t,n)){var o=t[n],a=he(o);if(re(o)||a){a&&(o=o["@list"]);for(var s=0;s0){var j=G(t,h);e.addValue(o,j,S)}}else{var S;if(oe(d))S=G(t,d,null,{vocab:"@type"===h});else{S=[];for(var E=0;E1&&!(2===S&&"@index"in s))throw new I('Invalid JSON-LD syntax; if an element has the property "@set" or "@list", then it can have at most one other property that is "@index".',"jsonld.SyntaxError",{code:"invalid set or list object",element:s});"@set"in s&&(s=s["@set"],S=(h=Object.keys(s)).length)}else 1===S&&"@language"in s&&(s=null);return!ne(s)||i.keepFreeFloatingNodes||o||null!==n&&"@graph"!==f||(0===S||"@value"in s||"@list"in s||1===S&&"@id"in s)&&(s=null),s},R.prototype.createNodeMap=function(e,t){var n={"@default":{}};return z(e,n,"@default",(t=t||{}).namer||t.issuer||new we("_:b")),H(n)},R.prototype.flatten=function(e){for(var t=this.createNodeMap(e),n=[],r=Object.keys(t).sort(),i=0;i=r.MAX_TOTAL_DEPTH)return n(new Error("Maximum total call stack depth exceeded; normalization aborting."));!function i(){if(r.depth===r.MAX_DEPTH)return r.depth=0,r.running=!1,e.nextTick(i);var o=(new Date).getTime();if(r.running||(r.start=(new Date).getTime(),r.deadline=r.start+r.timeSlice),o1)return o();var s=a[0];r.canonicalIssuer.getId(s),delete i[s],delete r.hashToBlankNodes[e],t=!0,o()},e)}],e)},e)},function(e){var t=Object.keys(r.hashToBlankNodes).sort();r.forEach(t,function(e,t,n){var i=[],o=r.hashToBlankNodes[e];r.waterfall([function(e){r.forEach(o,function(e,t,n){if(r.canonicalIssuer.hasId(e))return n();var o=new we("_:b");o.getId(e),r.hashNDegreeQuads(e,o,function(e,t){if(e)return n(e);i.push(t),n()})},e)},function(e){i.sort(function(e,t){return e.hasht.hash?1:0}),r.forEach(i,function(e,t,n){for(var i in e.issuer.existing)r.canonicalIssuer.getId(i);n()},e)}],n)},e)},function(e){var t=[];r.waterfall([function(e){r.forEach(r.quads,function(e,n,i){r.forEachComponent(e,function(e){"blank node"===e.type&&0!==e.value.indexOf(r.canonicalIssuer.prefix)&&(e.value=r.canonicalIssuer.getId(e.value))}),t.push(be(e)),i()},e)},function(e){if(t.sort(),"application/nquads"===r.options.format)return n=t.join(""),e();n=me(t.join("")),e()}],e)}],function(e){t(e,n)})},F.prototype.hashFirstDegreeQuads=function(e,t){var n=this,r=n.blankNodeInfo[e];if("hash"in r)return t(null,r.hash);var i=[],o=r.quads;n.forEach(o,function(t,r,o){var a={predicate:t.predicate};n.forEachComponent(t,function(t,r){a[r]=n.modifyFirstDegreeComponent(e,t,r)}),i.push(be(a)),o()},function(e){if(e)return t(e);i.sort(),r.hash=_e.hashNQuads(n.name,i),t(null,r.hash)})},F.prototype.modifyFirstDegreeComponent=function(e,t){return"blank node"!==t.type?t:((t=ve(t)).value=t.value===e?"_:a":"_:z",t)},F.prototype.hashRelatedBlankNode=function(e,t,n,r,i){var o,a=this;a.waterfall([function(t){return a.canonicalIssuer.hasId(e)?(o=a.canonicalIssuer.getId(e),t()):n.hasId(e)?(o=n.getId(e),t()):void a.hashFirstDegreeQuads(e,function(e,n){if(e)return t(e);o=n,t()})}],function(e){if(e)return i(e);var n=new _e(a.name);return n.update(r),"g"!==r&&n.update(a.getRelatedPredicate(t)),n.update(o),i(null,n.digest())})},F.prototype.getRelatedPredicate=function(e){return"<"+e.predicate.value+">"},F.prototype.hashNDegreeQuads=function(e,t,n){var r,i=this,o=new _e(i.name);i.waterfall([function(n){i.createHashToRelated(e,t,function(e,t){if(e)return n(e);r=t,n()})},function(e){var n=Object.keys(r).sort();i.forEach(n,function(e,n,a){o.update(e);var s,u="",l=new xe(r[e]);i.whilst(function(){return l.hasNext()},function(e){var n=l.next(),r=t.clone(),o="",a=[];i.waterfall([function(t){i.forEach(n,function(t,n,s){if(i.canonicalIssuer.hasId(t)?o+=i.canonicalIssuer.getId(t):(r.hasId(t)||a.push(t),o+=r.getId(t)),0!==u.length&&o.length>=u.length&&o>u)return e();s()},t)},function(t){i.forEach(a,function(t,n,a){i.hashNDegreeQuads(t,r,function(n,i){return n?a(n):(o+=r.getId(t),o+="<"+i.hash+">",r=i.issuer,0!==u.length&&o.length>=u.length&&o>u?e():void a())})},t)},function(e){(0===u.length||o=0;--n)if(t[n]["@id"]===e["@id"])return!0;return!1}function W(e,t,n){var r="@"+n,i=r in e?e[r][0]:t[n];return"embed"===n&&(!0===i?i="@last":!1===i?i="@never":"@always"!==i&&"@never"!==i&&"@link"!==i&&(i="@last")),i}function J(t,n,r){if("@type"in n&&(1!==n["@type"].length||!ne(n["@type"][0]))){for(var i=n["@type"],o=0;o=0;--p)for(var S=k[p],E=S.terms,O=0;O0&&a.length>s&&o[0]===a[0];)o.shift(),a.shift();var u="";if(o.length>0){o.pop();for(var l=0;l=(i=a[u].iri).length?"":i[r])in s?s[o].push(a[u]):s[o]=[a[u]];for(var t in s)""!==t&&n(s,t,r+1)}function r(e,t,n,r){r in n||(n[r]=t)}}function te(e){if(!oe(e))return!1;switch(e){case"@base":case"@context":case"@container":case"@default":case"@embed":case"@explicit":case"@graph":case"@id":case"@index":case"@language":case"@list":case"@omitDefault":case"@preserve":case"@requireAll":case"@reverse":case"@set":case"@type":case"@value":case"@vocab":return!0}return!1}function ne(e){return"[object Object]"===Object.prototype.toString.call(e)}function re(e){return Array.isArray(e)}function ie(e){if(!oe(e)&&!function(e){return ne(e)&&0===Object.keys(e).length}(e)){var t=!1;if(re(e)){t=!0;for(var n=0;n1||!("@id"in e));return t}function ce(e){return ne(e)&&1===Object.keys(e).length&&"@id"in e}function fe(e){return ne(e)&&"@value"in e}function he(e){return ne(e)&&"@list"in e}function de(e){var t=!1;return ne(e)&&(t="@id"in e?0===e["@id"].indexOf("_:"):0===Object.keys(e).length||!("@value"in e||"@set"in e||"@list"in e)),t}function pe(e){return oe(e)&&-1!==e.indexOf(":")}function ve(e){if(e&&"object"==typeof e){var t;if(re(e)){t=[];for(var n=0;nN)return r=new I("Maximum number of @context URLs exceeded.","jsonld.ContextUrlError",{code:"loading remote context failed",max:N}),a(r);var s={},u=function(){ye(e,s,!0,i),a(null,e)};if(!ye(e,s,!1,i))return u();var l=[];for(var c in s)!1===s[c]&&l.push(c);for(var f=l.length,h=0;h]*)>)|(_:(?:[A-Za-z0-9]+)))[ \\t]+(?:<([^:]+:[^>]*)>)[ \\t]+(?:(?:<([^:]+:[^>]*)>)|(_:(?:[A-Za-z0-9]+))|(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"(?:(?:\\^\\^(?:<([^:]+:[^>]*)>))|(?:@([a-z]+(?:-[a-z0-9]+)*)))?))[ \\t]*(?:\\.|(?:(?:(?:<([^:]+:[^>]*)>)|(_:(?:[A-Za-z0-9]+)))[ \\t]*\\.))[ \\t]*(?:#.*)?$'),r={},i=e.split(/(?:\r\n)|(?:\n)|(?:\r)/g),o=0,a=0;a":a+=n.value,a+=" ","IRI"===r.type?a+="<"+r.value+">":a+=r.value,a+=" ","IRI"===i.type)a+="<"+i.value+">";else if("blank node"===i.type)a+=i.value;else{a+='"'+i.value.replace(/\\/g,"\\\\").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\"/g,'\\"')+'"',i.datatype===E?i.language&&(a+="@"+i.language):i.datatype!==m&&(a+="^^<"+i.datatype+">")}return null!=o&&(0!==o.indexOf("_:")?a+=" <"+o+">":a+=" "+o),a+=" .\n"}function we(e){this.prefix=e,this.counter=0,this.existing={}}Object.keys||(Object.keys=function(e){if(e!==Object(e))throw new TypeError("Object.keys called on non-object");var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}),e.registerRDFParser("application/nquads",me),e.registerRDFParser("rdfa-api",function(e){for(var t={"@default":[]},n=e.getSubjects(),r=0;rt)&&(a&&i>0&&o>this.list[i-1]||!a&&ithis.list[i+1])&&(t=o,n=i)}if(null===t)this.done=!0;else{var s=this.left[t]?n-1:n+1;this.list[n]=this.list[s],this.list[s]=t;for(i=0;it&&(this.left[this.list[i]]=!this.left[this.list[i]])}return e};var _e=function(e){if(!(this instanceof _e))return new _e(e);if(-1===["URDNA2015","URGNA2012"].indexOf(e))throw new Error("Invalid RDF Dataset Normalization algorithm: "+e);_e._init.call(this,e)};if(_e.hashNQuads=function(e,t){for(var n=new _e(e),r=0;r0;)1&n&&(r._padding+=t),(n>>>=1)>0&&(t+=t)}this.start()};r.prototype.start=function(){this.messageLength=0,this.fullMessageLength=[];for(var e=this._algorithm.messageLengthSize/4,t=0;t>>0,t>>>0];for(var n=this.fullMessageLength.length-1;n>=0;--n)this.fullMessageLength[n]+=t[1],t[1]=t[0]+(this.fullMessageLength[n]/4294967296>>>0),this.fullMessageLength[n]=this.fullMessageLength[n]>>>0,t[0]=t[1]/4294967296>>>0;for(this._input.putBytes(e.bytes());this._input.length()>=this._algorithm.blockSize;)this.state=this._algorithm.digest(this.state,this._input);return(this._input.read>2048||0===this._input.length())&&this._input.compact(),this},r.prototype.digest=function(){var e=new r.ByteBuffer;e.putBytes(this._input.bytes());var t=this.fullMessageLength[this.fullMessageLength.length-1]+this._algorithm.messageLengthSize&this._algorithm.blockSize-1;e.putBytes(r._padding.substr(0,this._algorithm.blockSize-t));for(var n=new r.ByteBuffer,i=0;i>>28);this._algorithm.writeMessageLength(e,n);var o=this._algorithm.digest(this.state.copy(),e),a=new r.ByteBuffer;return o.write(a),a},r.ByteBuffer=function(e){this.data="string"==typeof e?e:"",this.read=0},r.ByteBuffer.prototype.putInt32=function(e){this.data+=String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)},r.ByteBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e},r.ByteBuffer.prototype.putBytes=function(e){this.data+=e},r.ByteBuffer.prototype.bytes=function(){return this.data.slice(this.read)},r.ByteBuffer.prototype.length=function(){return this.data.length-this.read},r.ByteBuffer.prototype.compact=function(){this.data=this.data.slice(this.read),this.read=0},r.ByteBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=64;){for(r=e.h0,o=e.h1,a=e.h2,s=e.h3,u=e.h4,l=0;l<16;++l)n=t.getInt32(),f[l]=n,n=(r<<5|r>>>27)+(s^o&(a^s))+u+1518500249+n,u=s,s=a,a=o<<30|o>>>2,o=r,r=n;for(;l<20;++l)n=(n=f[l-3]^f[l-8]^f[l-14]^f[l-16])<<1|n>>>31,f[l]=n,n=(r<<5|r>>>27)+(s^o&(a^s))+u+1518500249+n,u=s,s=a,a=o<<30|o>>>2,o=r,r=n;for(;l<32;++l)n=(n=f[l-3]^f[l-8]^f[l-14]^f[l-16])<<1|n>>>31,f[l]=n,n=(r<<5|r>>>27)+(o^a^s)+u+1859775393+n,u=s,s=a,a=o<<30|o>>>2,o=r,r=n;for(;l<40;++l)n=(n=f[l-6]^f[l-16]^f[l-28]^f[l-32])<<2|n>>>30,f[l]=n,n=(r<<5|r>>>27)+(o^a^s)+u+1859775393+n,u=s,s=a,a=o<<30|o>>>2,o=r,r=n;for(;l<60;++l)n=(n=f[l-6]^f[l-16]^f[l-28]^f[l-32])<<2|n>>>30,f[l]=n,n=(r<<5|r>>>27)+(o&a|s&(o^a))+u+2400959708+n,u=s,s=a,a=o<<30|o>>>2,o=r,r=n;for(;l<80;++l)n=(n=f[l-6]^f[l-16]^f[l-28]^f[l-32])<<2|n>>>30,f[l]=n,n=(r<<5|r>>>27)+(o^a^s)+u+3395469782+n,u=s,s=a,a=o<<30|o>>>2,o=r,r=n;e.h0=e.h0+r|0,e.h1=e.h1+o|0,e.h2=e.h2+a|0,e.h3=e.h3+s|0,e.h4=e.h4+u|0,c-=64}return e},i._createState=function(){var e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520,copy:function(){var t=i._createState();return t.h0=e.h0,t.h1=e.h1,t.h2=e.h2,t.h3=e.h3,t.h4=e.h4,t},write:function(t){t.putInt32(e.h0),t.putInt32(e.h1),t.putInt32(e.h2),t.putInt32(e.h3),t.putInt32(e.h4)}};return e};var o={_k:null,_w:null,Algorithm:function(){this.name="sha256",this.blockSize=64,this.digestLength=32,this.messageLengthSize=8}};o.Algorithm.prototype.start=function(){return o._k||o._init(),o._createState()},o.Algorithm.prototype.writeMessageLength=function(e,t){e.putBytes(t.bytes())},o.Algorithm.prototype.digest=function(e,t){for(var n,r,i,a,s,u,l,c,f,h,d,p,v,y=t.length(),g=o._k,m=o._w;y>=64;){for(s=0;s<16;++s)m[s]=t.getInt32();for(;s<64;++s)n=((n=m[s-2])>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,r=((r=m[s-15])>>>7|r<<25)^(r>>>18|r<<14)^r>>>3,m[s]=n+m[s-7]+r+m[s-16]|0;for(u=e.h0,l=e.h1,c=e.h2,f=e.h3,h=e.h4,d=e.h5,p=e.h6,v=e.h7,s=0;s<64;++s)i=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),a=u&l|c&(u^l),n=v+((h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(p^h&(d^p))+g[s]+m[s],v=p,p=d,d=h,h=f+n|0,f=c,c=l,l=u,u=n+(r=i+a)|0;e.h0=e.h0+u|0,e.h1=e.h1+l|0,e.h2=e.h2+c|0,e.h3=e.h3+f|0,e.h4=e.h4+h|0,e.h5=e.h5+d|0,e.h6=e.h6+p|0,e.h7=e.h7+v|0,y-=64}return e},o._createState=function(){var e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225,copy:function(){var t=o._createState();return t.h0=e.h0,t.h1=e.h1,t.h2=e.h2,t.h3=e.h3,t.h4=e.h4,t.h5=e.h5,t.h6=e.h6,t.h7=e.h7,t},write:function(t){t.putInt32(e.h0),t.putInt32(e.h1),t.putInt32(e.h2),t.putInt32(e.h3),t.putInt32(e.h4),t.putInt32(e.h5),t.putInt32(e.h6),t.putInt32(e.h7)}};return e},o._init=function(){o._k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],o._w=new Array(64)}}(u),!d)var ke=function(){d=n(41).XMLSerializer};function Te(e,t){var n="";0===e.indexOf("/")&&(n="/");for(var r=e.split("/"),i=[];r.length>0;)"."===r[0]||""===r[0]&&r.length>1?r.shift():".."!==r[0]?i.push(r.shift()):(r.shift(),t||i.length>0&&".."!==i[i.length-1]?i.pop():i.push(".."));return n+i.join("/")}if(e.url={},e.url.parsers={simple:{keys:["href","scheme","authority","path","query","fragment"],regex:/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/},full:{keys:["href","protocol","scheme","authority","auth","user","password","hostname","port","path","directory","file","query","fragment"],regex:/^(([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/}},e.url.parse=function(t,n){for(var r={},i=e.url.parsers[n||"full"],o=i.regex.exec(t),a=i.keys.length;a--;)r[i.keys[a]]=void 0===o[a]?null:o[a];return r.normalizedPath=Te(r.path,!!r.authority),r},u?e.useDocumentLoader("node"):"undefined"!=typeof XMLHttpRequest&&e.useDocumentLoader("xhr"),u){e.use=function(t){switch(t){case"request":e.request=n(13);break;default:throw new I("Unknown extension.","jsonld.UnknownExtension",{extension:t})}};var je={exports:{},filename:a};n(13)(je,"version"),e.version=je.exports.version}return e},f=function(){return c(function(){return f()})};!u&&n(64)?void 0===(s=function(){return c(f),f}.apply(t,[]))||(e.exports=s):(c(f),e.exports&&(e.exports=f),l&&("undefined"==typeof jsonld?jsonld=jsonldjs=f:jsonldjs=f))}()}).call(this,n(4),n(5),n(14).setImmediate,"/")},function(e,t,n){(function(r,i,o){var a; +/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.3.0 - */(function(){'use strict';function d(e){return'function'==typeof e||'object'==typeof e&&null!==e}function l(e){return'function'==typeof e}function p(e){return'object'==typeof e&&null!==e}function u(e){ie=e}function c(e){K=e}function h(){var e=a.nextTick,t=a.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);return Array.isArray(t)&&'0'===t[1]&&'10'===t[2]&&(e=r),function(){e(b)}}function f(){return function(){oe(b)}}function g(){var e=0,t=new te(b),n=document.createTextNode('');return t.observe(n,{characterData:!0}),function(){n.data=e=++e%2}}function m(){var e=new MessageChannel;return e.port1.onmessage=b,function(){e.port2.postMessage(0)}}function y(){return function(){setTimeout(b,1)}}function b(){for(var e=0;e<']=0,this._entityCount=0,this._blankNodeIndex=0,!t&&e&&!e[0]&&(t=e,e=null),this._prefixes=Object.create(null),t&&t.prefixes&&this.addPrefixes(t.prefixes),e&&this.addTriples(e)):new a(e,t)}var r=n(27).expandPrefixedName;a.prototype={get size(){var e=this._size;if(null!==e)return e;var t=this._graphs,n,a;for(var r in t)for(var o in n=t[r].subjects)for(var i in a=n[o])e+=Object.keys(a[i]).length;return this._size=e},_addToIndex:function(e,t,n,a){var r=e[t]||(e[t]={}),o=r[n]||(r[n]={});o[a]=null},_removeFromIndex:function(e,t,n,a){var r=e[t],o=r[n],i;for(i in delete o[a],o)return;for(i in delete r[n],r)return;delete e[t]},_findInIndex:function(e,t,n,a,r,o,i,s){var d=[],p=Object.keys(this._entities),u,c,h;for(var f in t&&((u=e,e={})[t]=u[t]),e){var g=p[f];if(c=e[f])for(var m in n&&((u=c,c={})[n]=u[n]),c){var y=p[m];if(h=c[m])for(var b=a?(a in h)?[a]:[]:Object.keys(h),x=b.length-1,l;0<=x;x--)l={subject:'',predicate:'',object:'',graph:s},l[r]=g,l[o]=y,l[i]=p[b[x]],d.push(l)}}return d},_countInIndex:function(e,t,n,a){var r=0,o,i,s;for(var d in t&&((o=e,e={})[t]=o[t]),e)if(i=e[d])for(var l in n&&((o=i,i={})[n]=o[n]),i)(s=i[l])&&(a?a in s&&r++:r+=Object.keys(s).length);return r},addTriple:function(e,t,n,a){t||(a=e.graph,n=e.object,t=e.predicate,e=e.subject),a=a||'';var r=this._graphs[a];r||(r=this._graphs[a]={subjects:{},predicates:{},objects:{}},Object.freeze(r));var o=this._entities;e=o[e]||(o[e]=++this._entityCount),t=o[t]||(o[t]=++this._entityCount),n=o[n]||(o[n]=++this._entityCount),this._addToIndex(r.subjects,e,t,n),this._addToIndex(r.predicates,t,n,e),this._addToIndex(r.objects,n,e,t),this._size=null},addTriples:function(e){for(var t=e.length-1;0<=t;t--)this.addTriple(e[t])},addPrefix:function(e,t){this._prefixes[e]=t},addPrefixes:function(e){for(var t in e)this.addPrefix(t,e[t])},removeTriple:function(e,t,n,a){t||(a=e.graph,n=e.object,t=e.predicate,e=e.subject),a=a||'';var r=this._entities,o=this._graphs,i;if((e=r[e])&&(t=r[t])&&(n=r[n])&&(i=o[a])){var s,d;if((s=i.subjects[e])&&(d=s[t])&&n in d){for(e in this._removeFromIndex(i.subjects,e,t,n),this._removeFromIndex(i.predicates,t,n,e),this._removeFromIndex(i.objects,n,e,t),null!==this._size&&this._size--,i.subjects)return;delete o[a]}}},removeTriples:function(e){for(var t=e.length-1;0<=t;t--)this.removeTriple(e[t])},find:function(e,t,n,a){var o=this._prefixes;return this.findByIRI(r(e,o),r(t,o),r(n,o),r(a,o))},findByIRI:function(e,t,n,a){a=a||'';var r=this._graphs[a],o=this._entities;return r?e&&!(e=o[e])?[]:t&&!(t=o[t])?[]:n&&!(n=o[n])?[]:e?n?this._findInIndex(r.objects,n,e,t,'object','subject','predicate',a):this._findInIndex(r.subjects,e,t,null,'subject','predicate','object',a):t?this._findInIndex(r.predicates,t,n,null,'predicate','object','subject',a):n?this._findInIndex(r.objects,n,null,null,'object','subject','predicate',a):this._findInIndex(r.subjects,null,null,null,'subject','predicate','object',a):[]},count:function(e,t,n,a){var o=this._prefixes;return this.countByIRI(r(e,o),r(t,o),r(n,o),r(a,o))},countByIRI:function(e,t,n,a){a=a||'';var r=this._graphs[a],o=this._entities;return r?e&&!(e=o[e])?0:t&&!(t=o[t])?0:n&&!(n=o[n])?0:e?n?this._countInIndex(r.objects,n,e,t):this._countInIndex(r.subjects,e,t,n):t?this._countInIndex(r.predicates,t,n,e):this._countInIndex(r.objects,n,e,t):0},createBlankNode:function(e){var t,n;if(e)for(t=e='_:'+e,n=1;this._entities[t];)t=e+n++;else do t='_:b'+this._blankNodeIndex++;while(this._entities[t]);return this._entities[t]=++this._entityCount,t}},e.exports=a},function(e,t,n){function a(e){if(!(this instanceof a))return new a(e);r.call(this,{decodeStrings:!0}),this._readableState.objectMode=!0;var t=this,n=new i(e);n.parse(function(e,n){n&&t.push(n)||e&&t.emit('error',e)},this.emit.bind(this,'prefix')),this._transform=function(e,t,a){n.addChunk(e),a()},this._flush=function(e){n.end(),e()}}var r=n(45).Transform,o=n(53),i=n(26);o.inherits(a,r),e.exports=a},function(e,t,n){function a(){r.call(this)}e.exports=a;var r=n(28).EventEmitter,o=n(7);o(a,r),a.Readable=n(29),a.Writable=n(73),a.Duplex=n(74),a.Transform=n(75),a.PassThrough=n(76),a.Stream=a,a.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&l.pause&&l.pause()}function a(){l.readable&&l.resume&&l.resume()}function o(){p||(p=!0,e.end())}function i(){p||(p=!0,'function'==typeof e.destroy&&e.destroy())}function s(e){if(d(),0===r.listenerCount(this,'error'))throw e}function d(){l.removeListener('data',n),e.removeListener('drain',a),l.removeListener('end',o),l.removeListener('close',i),l.removeListener('error',s),e.removeListener('error',s),l.removeListener('end',d),l.removeListener('close',d),e.removeListener('close',d)}var l=this;l.on('data',n),e.on('drain',a),e._isStdio||t&&!1===t.end||(l.on('end',o),l.on('close',i));var p=!1;return l.on('error',s),e.on('error',s),l.on('end',d),l.on('close',d),e.on('close',d),e.emit('pipe',l),e}},function(e,t,n){'use strict';(function(t,r){function o(e){return F.from(e)}function i(e){return F.isBuffer(e)||e instanceof B}function s(e,t,n){return'function'==typeof e.prependListener?e.prependListener(t,n):void(e._events&&e._events[t]?D(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n))}function d(e,t){U=U||n(8),e=e||{};var r=t instanceof U;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var o=e.highWaterMark,i=e.readableHighWaterMark,s=this.objectMode?16:16384;this.highWaterMark=o||0===o?o:r&&(i||0===i)?i:s,this.highWaterMark=a(this.highWaterMark),this.buffer=new V,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||'utf8',this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(!W&&(W=n(51).StringDecoder),this.decoder=new W(e.encoding),this.encoding=e.encoding)}function l(e){return U=U||n(8),this instanceof l?void(this._readableState=new d(e,this),this.readable=!0,e&&('function'==typeof e.read&&(this._read=e.read),'function'==typeof e.destroy&&(this._destroy=e.destroy)),M.call(this)):new l(e)}function p(e,t,n,a,r){var i=e._readableState;if(null===t)i.reading=!1,m(e,i);else{var s;r||(s=c(i,t)),s?e.emit('error',s):i.objectMode||t&&0=Y?e=Y:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function g(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e===e?(e>t.highWaterMark&&(t.highWaterMark=f(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function m(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,y(e)}}function y(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(z('emitReadable',t.flowing),t.emittedReadable=!0,t.sync?E.nextTick(b,e):b(e))}function b(e){z('emit readable'),e.emit('readable'),N(e)}function x(e,t){t.readingMore||(t.readingMore=!0,E.nextTick(_,e,t))}function _(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(a=t.decoder?t.buffer.join(''):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):a=S(e,t.buffer,t.decoder),a}function S(e,t,n){var a;return eo.length?o.length:e;if(r+=i===o.length?o:o.slice(0,e),e-=i,0===e){i===o.length?(++a,t.head=n.next?n.next:t.tail=null):(t.head=n,n.data=o.slice(i));break}++a}return t.length-=a,r}function R(e,t){var n=F.allocUnsafe(e),a=t.head,r=1;for(a.data.copy(n),e-=a.data.length;a=a.next;){var o=a.data,i=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,i),e-=i,0===e){i===o.length?(++r,t.head=a.next?a.next:t.tail=null):(t.head=a,a.data=o.slice(i));break}++r}return t.length-=r,n}function C(e){var t=e._readableState;if(0=t.highWaterMark||t.ended))return z('read: emitReadable',t.length,t.ended),0===t.length&&t.ended?C(this):y(this),null;if(e=g(e,t),0===e&&t.ended)return 0===t.length&&C(this),null;var a=t.needReadable;z('need readable',a),(0===t.length||t.length-ee)throw new RangeError('"size" argument must not be negative')}function c(e,t,n,a){return u(t),0>=t?d(e,t):void 0===n?d(e,t):'string'==typeof a?d(e,t).fill(n,a):d(e,t).fill(n)}function h(e,t){if(u(t),e=d(e,0>t?0:0|b(t)),!l.TYPED_ARRAY_SUPPORT)for(var n=0;nt.length?0:0|b(t.length);e=d(e,n);for(var a=0;an||t.byteLength=s())throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x'+s().toString(16)+' bytes');return 0|e}function x(e){return+e!=e&&(e=0),l.alloc(+e)}function _(e,t){if(l.isBuffer(e))return e.length;if('undefined'!=typeof ArrayBuffer&&'function'==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;'string'!=typeof e&&(e=''+e);var n=e.length;if(0===n)return 0;for(var a=!1;;)switch(t){case'ascii':case'latin1':case'binary':return n;case'utf8':case'utf-8':case void 0:return Y(e).length;case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return 2*n;case'hex':return n>>>1;case'base64':return K(e).length;default:if(a)return Y(e).length;t=(''+t).toLowerCase(),a=!0;}}function v(e,t,n){var a=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return'';if((void 0===n||n>this.length)&&(n=this.length),0>=n)return'';if(n>>>=0,t>>>=0,n<=t)return'';for(e||(e='utf8');!0;)switch(e){case'hex':return A(this,t,n);case'utf8':case'utf-8':return O(this,t,n);case'ascii':return D(this,t,n);case'latin1':case'binary':return U(this,t,n);case'base64':return L(this,t,n);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return P(this,t,n);default:if(a)throw new TypeError('Unknown encoding: '+e);e=(e+'').toLowerCase(),a=!0;}}function w(e,t,n){var a=e[t];e[t]=e[n],e[n]=a}function k(e,t,n,a,r){if(0===e.length)return-1;if('string'==typeof n?(a=n,n=0):2147483647n&&(n=-2147483648),n=+n,isNaN(n)&&(n=r?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(0>n)if(r)n=0;else return-1;if('string'==typeof t&&(t=l.from(t,a)),l.isBuffer(t))return 0===t.length?-1:T(e,t,n,a,r);if('number'==typeof t)return t&=255,l.TYPED_ARRAY_SUPPORT&&'function'==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):T(e,[t],n,a,r);throw new TypeError('val must be string, number or Buffer')}function T(e,t,n,a,r){function o(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}var s=1,d=e.length,l=t.length;if(void 0!==a&&(a=(a+'').toLowerCase(),'ucs2'===a||'ucs-2'===a||'utf16le'===a||'utf-16le'===a)){if(2>e.length||2>t.length)return-1;s=2,d/=2,l/=2,n/=2}var p;if(r){var i=-1;for(p=n;pd&&(n=d-l),p=n;0<=p;p--){for(var u=!0,c=0;cr&&(a=r)):a=r;var o=t.length;if(0!=o%2)throw new TypeError('Invalid hex string');a>o/2&&(a=o/2);for(var s=0,i;so&&(i=o):2==s?(d=e[r+1],128==(192&d)&&(u=(31&o)<<6|63&d,127u||57343u&&(i=u))):void 0}null===i?(i=65533,s=1):65535>>10),i=56320|1023&i),a.push(i),r+=s}return E(a)}function E(e){var t=e.length;if(t<=oe)return r.apply(String,e);for(var n='',a=0;at)&&(t=0),(!n||0>n||n>a)&&(n=a);for(var r='',o=t;oe)throw new RangeError('offset is not uint');if(e+t>n)throw new RangeError('Trying to access beyond buffer length')}function F(e,t,n,a,r,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError('Index out of range')}function B(e,t,n,a){0>t&&(t=65535+t+1);for(var r=0,o=te(e.length-n,2);r>>8*(a?r:1-r)}function q(e,t,n,a){0>t&&(t=4294967295+t+1);for(var r=0,o=te(e.length-n,4);r>>8*(a?r:3-r)}function H(e,t,n,a,r,o){if(n+a>e.length)throw new RangeError('Index out of range');if(0>n)throw new RangeError('Index out of range')}function z(e,t,n,a,r){return r||H(e,t,n,4,34028234663852886e22,-34028234663852886e22),ae.write(e,t,n,a,23,4),n+4}function V(e,t,n,a,r){return r||H(e,t,n,8,17976931348623157e292,-17976931348623157e292),ae.write(e,t,n,a,52,8),n+8}function X(e){if(e=W(e).replace(ie,''),2>e.length)return'';for(;0!=e.length%4;)e+='=';return e}function W(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,'')}function J(e){return 16>e?'0'+e.toString(16):e.toString(16)}function Y(e,t){t=t||Infinity;for(var n=e.length,a=null,r=[],o=0,i;oi){if(!a){if(56319i){-1<(t-=3)&&r.push(239,191,189),a=i;continue}i=(a-55296<<10|i-56320)+65536}else a&&-1<(t-=3)&&r.push(239,191,189);if(a=null,128>i){if(0>(t-=1))break;r.push(i)}else if(2048>i){if(0>(t-=2))break;r.push(192|i>>6,128|63&i)}else if(65536>i){if(0>(t-=3))break;r.push(224|i>>12,128|63&i>>6,128|63&i)}else if(1114112>i){if(0>(t-=4))break;r.push(240|i>>18,128|63&i>>12,128|63&i>>6,128|63&i)}else throw new Error('Invalid code point')}return r}function Q(e){for(var t=[],n=0;n(t-=2));++a)r=e.charCodeAt(a),o=r>>8,i=r%256,n.push(i),n.push(o);return n}function K(e){return ne.toByteArray(X(e))}function Z(e,t,n,a){for(var r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function ee(e){return e!==e}var te=Math.min,ne=o(66),ae=o(67),re=o(47);/*! + */ +(function(){"use strict";function s(e){return"function"==typeof e}var u,l,c=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},f=0,h=function(e,t){S[f]=e,S[f+1]=t,2===(f+=2)&&(l?l(E):b())};var d="undefined"!=typeof window?window:void 0,p=d||{},v=p.MutationObserver||p.WebKitMutationObserver,y=void 0!==r&&"[object process]"==={}.toString.call(r),g="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function m(){return function(){setTimeout(E,1)}}var b,w,x,_,k,T,j,S=new Array(1e3);function E(){for(var e=0;e<"]=0,this._entityCount=0,this._blankNodeIndex=0,t||!e||e[0]||(t=e,e=null),this._prefixes=Object.create(null),t&&t.prefixes&&this.addPrefixes(t.prefixes),e&&this.addTriples(e)}i.prototype={get size(){var e=this._size;if(null!==e)return e;var t,n,r=this._graphs;for(var i in r)for(var o in t=r[i].subjects)for(var a in n=t[o])e+=Object.keys(n[a]).length;return this._size=e},_addToIndex:function(e,t,n,r){var i=e[t]||(e[t]={});(i[n]||(i[n]={}))[r]=null},_removeFromIndex:function(e,t,n,r){var i,o=e[t],a=o[n];for(i in delete a[r],a)return;for(i in delete o[n],o)return;delete e[t]},_findInIndex:function(e,t,n,r,i,o,a,s){var u,l,c,f=[],h=Object.keys(this._entities);for(var d in t&&((u=e,e={})[t]=u[t]),e){var p=h[d];if(l=e[d])for(var v in n&&((u=l,l={})[n]=u[n]),l){var y=h[v];if(c=l[v])for(var g=(r?r in c?[r]:[]:Object.keys(c)),m=g.length-1;m>=0;m--){var b={subject:"",predicate:"",object:"",graph:s};b[i]=p,b[o]=y,b[a]=h[g[m]],f.push(b)}}}return f},_countInIndex:function(e,t,n,r){var i,o,a,s=0;for(var u in t&&((i=e,e={})[t]=i[t]),e)if(o=e[u])for(var l in n&&((i=o,o={})[n]=i[n]),o)(a=o[l])&&(r?r in a&&s++:s+=Object.keys(a).length);return s},addTriple:function(e,t,n,r){t||(r=e.graph,n=e.object,t=e.predicate,e=e.subject),r=r||"";var i=this._graphs[r];i||(i=this._graphs[r]={subjects:{},predicates:{},objects:{}},Object.freeze(i));var o=this._entities;e=o[e]||(o[e]=++this._entityCount),t=o[t]||(o[t]=++this._entityCount),n=o[n]||(o[n]=++this._entityCount),this._addToIndex(i.subjects,e,t,n),this._addToIndex(i.predicates,t,n,e),this._addToIndex(i.objects,n,e,t),this._size=null},addTriples:function(e){for(var t=e.length-1;t>=0;t--)this.addTriple(e[t])},addPrefix:function(e,t){this._prefixes[e]=t},addPrefixes:function(e){for(var t in e)this.addPrefix(t,e[t])},removeTriple:function(e,t,n,r){t||(r=e.graph,n=e.object,t=e.predicate,e=e.subject),r=r||"";var i,o,a,s=this._entities,u=this._graphs;if((e=s[e])&&((t=s[t])&&(n=s[n])&&(i=u[r])&&(o=i.subjects[e])&&(a=o[t])&&n in a)){for(e in this._removeFromIndex(i.subjects,e,t,n),this._removeFromIndex(i.predicates,t,n,e),this._removeFromIndex(i.objects,n,e,t),null!==this._size&&this._size--,i.subjects)return;delete u[r]}},removeTriples:function(e){for(var t=e.length-1;t>=0;t--)this.removeTriple(e[t])},find:function(e,t,n,i){var o=this._prefixes;return this.findByIRI(r(e,o),r(t,o),r(n,o),r(i,o))},findByIRI:function(e,t,n,r){r=r||"";var i=this._graphs[r],o=this._entities;return i?e&&!(e=o[e])?[]:t&&!(t=o[t])?[]:n&&!(n=o[n])?[]:e?n?this._findInIndex(i.objects,n,e,t,"object","subject","predicate",r):this._findInIndex(i.subjects,e,t,null,"subject","predicate","object",r):t?this._findInIndex(i.predicates,t,n,null,"predicate","object","subject",r):n?this._findInIndex(i.objects,n,null,null,"object","subject","predicate",r):this._findInIndex(i.subjects,null,null,null,"subject","predicate","object",r):[]},count:function(e,t,n,i){var o=this._prefixes;return this.countByIRI(r(e,o),r(t,o),r(n,o),r(i,o))},countByIRI:function(e,t,n,r){r=r||"";var i=this._graphs[r],o=this._entities;return i?e&&!(e=o[e])?0:t&&!(t=o[t])?0:n&&!(n=o[n])?0:e?n?this._countInIndex(i.objects,n,e,t):this._countInIndex(i.subjects,e,t,n):t?this._countInIndex(i.predicates,t,n,e):this._countInIndex(i.objects,n,e,t):0},createBlankNode:function(e){var t,n;if(e)for(t=e="_:"+e,n=1;this._entities[t];)t=e+n++;else do{t="_:b"+this._blankNodeIndex++}while(this._entities[t]);return this._entities[t]=++this._entityCount,t}},e.exports=i},function(e,t,n){var r=n(45).Transform,i=n(53),o=n(26);function a(e){if(!(this instanceof a))return new a(e);r.call(this,{decodeStrings:!0}),this._readableState.objectMode=!0;var t=this,n=new o(e);n.parse(function(e,n){n&&t.push(n)||e&&t.emit("error",e)},this.emit.bind(this,"prefix")),this._transform=function(e,t,r){n.addChunk(e),r()},this._flush=function(e){n.end(),e()}}i.inherits(a,r),e.exports=a},function(e,t,n){e.exports=i;var r=n(28).EventEmitter;function i(){r.call(this)}n(7)(i,r),i.Readable=n(29),i.Writable=n(73),i.Duplex=n(74),i.Transform=n(75),i.PassThrough=n(76),i.Stream=i,i.prototype.pipe=function(e,t){var n=this;function i(t){e.writable&&!1===e.write(t)&&n.pause&&n.pause()}function o(){n.readable&&n.resume&&n.resume()}n.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(n.on("end",s),n.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function l(e){if(c(),0===r.listenerCount(this,"error"))throw e}function c(){n.removeListener("data",i),e.removeListener("drain",o),n.removeListener("end",s),n.removeListener("close",u),n.removeListener("error",l),e.removeListener("error",l),n.removeListener("end",c),n.removeListener("close",c),e.removeListener("close",c)}return n.on("error",l),e.on("error",l),n.on("end",c),n.on("close",c),e.on("close",c),e.emit("pipe",n),e}},function(e,t,n){"use strict";(function(t,r){var i=n(19);e.exports=b;var o,a=n(47);b.ReadableState=m;n(28).EventEmitter;var s=function(e,t){return e.listeners(t).length},u=n(48),l=n(20).Buffer,c=t.Uint8Array||function(){};var f=n(15);f.inherits=n(7);var h=n(68),d=void 0;d=h&&h.debuglog?h.debuglog("stream"):function(){};var p,v=n(69),y=n(50);f.inherits(b,u);var g=["error","close","destroy","pause","resume"];function m(e,t){e=e||{};var r=t instanceof(o=o||n(8));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,a=e.readableHighWaterMark,s=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(a||0===a)?a:s,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new v,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(p||(p=n(51).StringDecoder),this.decoder=new p(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(8),!(this instanceof b))return new b(e);this._readableState=new m(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),u.call(this)}function w(e,t,n,r,i){var o,a=e._readableState;null===t?(a.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,T(e)}(e,a)):(i||(o=function(e,t){var n;r=t,l.isBuffer(r)||r instanceof c||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(a,t)),o?e.emit("error",o):a.objectMode||t&&t.length>0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===l.prototype||(t=function(e){return l.from(e)}(t)),r?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):x(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||0!==t.length?x(e,a,t,!1):S(e,a)):x(e,a,t,!1))):r||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=_?e=_:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function T(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i.nextTick(j,e):j(e))}function j(e){d("emit readable"),e.emit("readable"),I(e)}function S(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(E,e,t))}function E(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}(e,t):function(e,t){var n=l.allocUnsafe(e),r=t.head,i=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),0===(e-=a)){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function C(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i.nextTick(L,t,e))}function L(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function A(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?C(this):T(this),null;if(0===(e=k(e,t))&&t.ended)return 0===t.length&&C(this),null;var r,i=t.needReadable;return d("need readable",i),(0===t.length||t.length-e0?R(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&C(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?c:b;function l(t,r){d("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,d("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",f),e.removeListener("error",y),e.removeListener("unpipe",l),n.removeListener("end",c),n.removeListener("end",b),n.removeListener("data",v),h=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function c(){d("onend"),e.end()}o.endEmitted?i.nextTick(u):n.once("end",u),e.on("unpipe",l);var f=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,I(e))}}(n);e.on("drain",f);var h=!1;var p=!1;function v(t){d("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==A(o.pipes,e))&&!h&&(d("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function y(t){d("onerror",t),b(),e.removeListener("error",y),0===s(e,"error")&&e.emit("error",t)}function g(){e.removeListener("finish",m),b()}function m(){d("onfinish"),e.removeListener("close",g),b()}function b(){d("unpipe"),n.unpipe(e)}return n.on("data",v),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",y),e.once("close",g),e.once("finish",m),e.emit("pipe",n),o.flowing||(d("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o * @license MIT - */t.Buffer=l,t.SlowBuffer=x,t.INSPECT_MAX_BYTES=50,l.TYPED_ARRAY_SUPPORT=e.TYPED_ARRAY_SUPPORT===void 0?i():e.TYPED_ARRAY_SUPPORT,t.kMaxLength=s(),l.poolSize=8192,l._augment=function(e){return e.__proto__=l.prototype,e},l.from=function(e,t,n){return p(null,e,t,n)},l.TYPED_ARRAY_SUPPORT&&(l.prototype.__proto__=Uint8Array.prototype,l.__proto__=Uint8Array,'undefined'!=typeof Symbol&&Symbol.species&&l[Symbol.species]===l&&Object.defineProperty(l,Symbol.species,{value:null,configurable:!0})),l.alloc=function(e,t,n){return c(null,e,t,n)},l.allocUnsafe=function(e){return h(null,e)},l.allocUnsafeSlow=function(e){return h(null,e)},l.isBuffer=function e(t){return!!(null!=t&&t._isBuffer)},l.compare=function e(t,n){if(!l.isBuffer(t)||!l.isBuffer(n))throw new TypeError('Arguments must be Buffers');if(t===n)return 0;for(var a=t.length,r=n.length,o=0,i=te(a,r);oa&&(n+=' ... ')),''},l.prototype.compare=function e(t,n,a,r,o){if(!l.isBuffer(t))throw new TypeError('Argument must be a Buffer');if(void 0===n&&(n=0),void 0===a&&(a=t?t.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),0>n||a>t.length||0>r||o>this.length)throw new RangeError('out of range index');if(r>=o&&n>=a)return 0;if(r>=o)return-1;if(n>=a)return 1;if(n>>>=0,a>>>=0,r>>>=0,o>>>=0,this===t)return 0;for(var s=o-r,d=a-n,p=te(s,d),u=this.slice(r,o),c=t.slice(n,a),h=0;ho)&&(a=o),0a||0>n)||n>this.length)throw new RangeError('Attempt to write outside buffer bounds');r||(r='utf8');for(var i=!1;;)switch(r){case'hex':return N(this,t,n,a);case'utf8':case'utf-8':return I(this,t,n,a);case'ascii':return S(this,t,n,a);case'latin1':case'binary':return j(this,t,n,a);case'base64':return R(this,t,n,a);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return C(this,t,n,a);default:if(i)throw new TypeError('Unknown encoding: '+r);r=(''+r).toLowerCase(),i=!0;}},l.prototype.toJSON=function e(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)}};var oe=4096;l.prototype.slice=function e(t,n){var a=this.length;t=~~t,n=n===void 0?a:~~n,0>t?(t+=a,0>t&&(t=0)):t>a&&(t=a),0>n?(n+=a,0>n&&(n=0)):n>a&&(n=a),n=s&&(o-=n(2,8*a)),o},l.prototype.readIntBE=function e(t,a,r){t|=0,a|=0,r||M(t,a,this.length);for(var o=a,i=1,s=this[t+--o];0=i&&(s-=n(2,8*a)),s},l.prototype.readInt8=function e(t,n){return n||M(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},l.prototype.readInt16LE=function e(t,n){n||M(t,2,this.length);var a=this[t]|this[t+1]<<8;return 32768&a?4294901760|a:a},l.prototype.readInt16BE=function e(t,n){n||M(t,2,this.length);var a=this[t+1]|this[t]<<8;return 32768&a?4294901760|a:a},l.prototype.readInt32LE=function e(t,n){return n||M(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},l.prototype.readInt32BE=function e(t,n){return n||M(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},l.prototype.readFloatLE=function e(t,n){return n||M(t,4,this.length),ae.read(this,t,!0,23,4)},l.prototype.readFloatBE=function e(t,n){return n||M(t,4,this.length),ae.read(this,t,!1,23,4)},l.prototype.readDoubleLE=function e(t,n){return n||M(t,8,this.length),ae.read(this,t,!0,52,8)},l.prototype.readDoubleBE=function e(t,n){return n||M(t,8,this.length),ae.read(this,t,!1,52,8)},l.prototype.writeUIntLE=function e(t,a,r,o){if(t=+t,a|=0,r|=0,!o){var s=n(2,8*r)-1;F(this,t,a,r,s,0)}var d=1,l=0;for(this[a]=255&t;++l>>8):B(this,t,n,!0),n+2},l.prototype.writeUInt16BE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):B(this,t,n,!1),n+2},l.prototype.writeUInt32LE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[n+3]=t>>>24,this[n+2]=t>>>16,this[n+1]=t>>>8,this[n]=255&t):q(this,t,n,!0),n+4},l.prototype.writeUInt32BE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):q(this,t,n,!1),n+4},l.prototype.writeIntLE=function e(t,a,r,o){if(t=+t,a|=0,!o){var s=n(2,8*r-1);F(this,t,a,r,s-1,-s)}var d=0,i=1,l=0;for(this[a]=255&t;++dt&&0==l&&0!==this[a+d-1]&&(l=1),this[a+d]=255&(t/i>>0)-l;return a+r},l.prototype.writeIntBE=function e(t,a,r,o){if(t=+t,a|=0,!o){var s=n(2,8*r-1);F(this,t,a,r,s-1,-s)}var d=r-1,i=1,l=0;for(this[a+d]=255&t;0<=--d&&(i*=256);)0>t&&0==l&&0!==this[a+d+1]&&(l=1),this[a+d]=255&(t/i>>0)-l;return a+r},l.prototype.writeInt8=function e(t,n,r){return t=+t,n|=0,r||F(this,t,n,1,127,-128),l.TYPED_ARRAY_SUPPORT||(t=a(t)),0>t&&(t=255+t+1),this[n]=255&t,n+1},l.prototype.writeInt16LE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):B(this,t,n,!0),n+2},l.prototype.writeInt16BE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):B(this,t,n,!1),n+2},l.prototype.writeInt32LE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8,this[n+2]=t>>>16,this[n+3]=t>>>24):q(this,t,n,!0),n+4},l.prototype.writeInt32BE=function e(t,n,a){return t=+t,n|=0,a||F(this,t,n,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),l.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):q(this,t,n,!1),n+4},l.prototype.writeFloatLE=function e(t,n,a){return z(this,t,n,!0,a)},l.prototype.writeFloatBE=function e(t,n,a){return z(this,t,n,!1,a)},l.prototype.writeDoubleLE=function e(t,n,a){return V(this,t,n,!0,a)},l.prototype.writeDoubleBE=function e(t,n,a){return V(this,t,n,!1,a)},l.prototype.copy=function e(t,n,a,r){if(a||(a=0),r||0===r||(r=this.length),n>=t.length&&(n=t.length),n||(n=0),0n)throw new RangeError('targetStart out of bounds');if(0>a||a>=this.length)throw new RangeError('sourceStart out of bounds');if(0>r)throw new RangeError('sourceEnd out of bounds');r>this.length&&(r=this.length),t.length-no||!l.TYPED_ARRAY_SUPPORT)for(s=0;so&&(t=o)}if(void 0!==r&&'string'!=typeof r)throw new TypeError('encoding must be a string');if('string'==typeof r&&!l.isEncoding(r))throw new TypeError('Unknown encoding: '+r)}else'number'==typeof t&&(t&=255);if(0>n||this.length>>=0,a=a===void 0?this.length:a>>>0,t||(t=0);var s;if('number'==typeof t)for(s=n;s=e)return 0;return 6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function d(e,t,n){var a=t.length-1;if(a=a)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString('utf16le',t,e.length-1)}function h(e){var t=e&&e.length?this.write(e):'';if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString('utf16le',0,n)}return t}function f(e,t){var a=(e.length-t)%3;return 0==a?e.toString('base64',t):(this.lastNeed=3-a,this.lastTotal=3,1==a?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString('base64',t,e.length-a))}function g(e){var t=e&&e.length?this.write(e):'';return this.lastNeed?t+this.lastChar.toString('base64',0,3-this.lastNeed):t}function m(e){return e.toString(this.encoding)}function y(e){return e&&e.length?this.write(e):''}var b=n(19).Buffer,x=b.isEncoding||function(e){switch(e=''+e,e&&e.toLowerCase()){case'hex':case'utf8':case'utf-8':case'ascii':case'binary':case'base64':case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':case'raw':return!0;default:return!1;}};;t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return'';var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return'';n=this.lastNeed,this.lastNeed=0}else n=0;return nr)return w(a)?e.stylize(RegExp.prototype.toString.call(a),'regexp'):e.stylize('[Object]','special');e.seen.push(a);var n;return n=x?u(e,a,r,m,g):g.map(function(t){return c(e,a,r,m,t,x)}),e.seen.pop(),h(n,b,v)}function l(e,t){if(v(t))return e.stylize('undefined','undefined');if(_(t)){var n='\''+JSON.stringify(t).replace(/^"|"$/g,'').replace(/'/g,'\\\'').replace(/\\"/g,'"')+'\'';return e.stylize(n,'string')}return b(t)?e.stylize(''+t,'number'):g(t)?e.stylize(''+t,'boolean'):m(t)?e.stylize('null','null'):void 0}function p(e){return'['+Error.prototype.toString.call(e)+']'}function u(e,t,n,a,r){for(var o=[],s=0,i=t.length;se.seen.indexOf(l.value)?(s=m(n)?d(e,l.value,null):d(e,l.value,n-1),-1e?'0'+e.toString(10):e.toString(10)}function C(){var e=new Date,t=[R(e.getHours()),R(e.getMinutes()),R(e.getSeconds())].join(':');return[e.getDate(),U[e.getMonth()],t].join(' ')}function L(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var O=/%[sdj%]/g;t.format=function(e){if(!_(e)){for(var t=[],n=0;n=o)return e;switch(e){case'%s':return a[n++]+'';case'%d':return+a[n++];case'%j':try{return JSON.stringify(a[n++])}catch(e){return'[Circular]'}default:return e;}}),s=a[n];n as '+a+':\n'+r+':\n'+r.stack)}function y(e,n){e&&f(e,t);try{k.parse(n,b)}catch(e){f(e,t)}}function b(e,n,a){if(e&&f(e,t),n)T.push(n);else{for(var r=0;r: Bad syntax:\n '+o+'\n at: "'+a.slice(r,r+30)+'"'},u,i,c;u=0;var h=t.sym(n+'#query');for(l.query=h;!0;){if(i=d.skipSpace(e,u),0>i)return l;if(';'===e[i]){if(u=d.skipSpace(e,i+1),0>u)return l;i=u}var f=!1;for(c=0;cu)throw p(d._thisDoc,d.lines,e,i+g.length,'found EOF, needed {...} after '+g);if(('INSERT'===g||'DELETE'===g)&&'DATA'===e.slice(u,u+4)){if(i=d.skipSpace(e,u+4),0>i)throw p(d._thisDoc,d.lines,e,u+4,'needed {...} after INSERT DATA '+g);u=i}var m=[];if(i=d.node(e,u,m),0>i)throw p(d._thisDoc,d.lines,e,u,'bad syntax or EOF in {...} after '+g);l[g.toLowerCase()]=m[0],t.add(h,s(g.toLowerCase()),m[0]),f=!0,u=i}}if(!f&&'@prefix'===e.slice(i,i+7)){if(u=d.directive(e,i),0>u)throw p(d._thisDoc,d.lines,e,u,'bad syntax or EOF after @prefix ');u=d.checkDot(e,u),f=!0}if(!f)throw p(d._thisDoc,d.lines,e,i,'Unknown syntax at start of statememt: \''+e.slice(i).slice(0,20)+'\'')}}e.exports=a;var r=n(24),o=n(16)},function(e,t,n){function a(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function r(e,t){for(var n=0,a;n=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function p(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function v(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function y(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=u.from(t,r)),u.isBuffer(t))return 0===t.length?-1:g(e,t,n,r,i);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):g(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function g(e,t,n,r,i){var o,a=1,s=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var c=-1;for(o=n;os&&(n=s-u),o=n;o>=0;o--){for(var f=!0,h=0;hi&&(r=i):r=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function T(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function j(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?4:l>223?3:l>191?2:1;if(i+f<=n)switch(f){case 1:l<128&&(c=l);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&l)<<6|63&o)>127&&(c=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&l)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&l)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,f=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),i+=f}return function(e){var t=e.length;if(t<=S)return String.fromCharCode.apply(String,e);var n="",r=0;for(;rthis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return j(this,t,n);case"ascii":return E(this,t,n);case"latin1":case"binary":return O(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},u.prototype.compare=function(e,t,n,r,i){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),s=Math.min(o,a),l=this.slice(r,i),c=e.slice(t,n),f=0;fi)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return m(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return w(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var S=4096;function E(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;ir)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,n,r,i,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function L(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function A(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function D(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,o){return o||D(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function P(e,t,n,r,o){return o||D(e,0,n,8),i.write(e,t,n,r,52,8),n+8}u.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(i*=256);)r+=this[e+--t]*i;return r},u.prototype.readUInt8=function(e,t){return t||R(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||R(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||R(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||R(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||R(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||R(e,t,this.length);for(var r=this[e],i=1,o=0;++o=(i*=128)&&(r-=Math.pow(2,8*t)),r},u.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||R(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},u.prototype.readInt8=function(e,t){return t||R(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||R(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(e,t){t||R(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(e,t){return t||R(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||R(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||R(e,4,this.length),i.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||R(e,4,this.length),i.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||R(e,8,this.length),i.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||R(e,8,this.length),i.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||C(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+n},u.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):A(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):A(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);C(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},u.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);C(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):A(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):A(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return P(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return P(this,e,t,!1,n)},u.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function q(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(M,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(5))},function(e,t,n){"use strict";var r=n(19);function i(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var n=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||r.nextTick(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(r.nextTick(i,n,e),n._writableState&&(n._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},function(e,t,n){"use strict";var r=n(20).Buffer,i=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=l,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=c,this.end=f,t=3;break;default:return this.write=h,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return i>0&&(e.lastNeed=i-1),i;if(--r=0)return i>0&&(e.lastNeed=i-2),i;if(--r=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=a;var r=n(8),i=n(15);function o(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),u=r[n];n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),p(n)?r.showHidden=n:n&&t._extend(r,n),m(r.showHidden)&&(r.showHidden=!1),m(r.depth)&&(r.depth=2),m(r.colors)&&(r.colors=!1),m(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=u),c(r,e,r.depth)}function u(e,t){var n=s.styles[t];return n?"["+s.colors[n][0]+"m"+e+"["+s.colors[n][1]+"m":e}function l(e,t){return e}function c(e,n,r){if(e.customInspect&&n&&k(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(r,e);return g(i)||(i=c(e,i,r)),i}var o=function(e,t){if(m(t))return e.stylize("undefined","undefined");if(g(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(v(t))return e.stylize("null","null")}(e,n);if(o)return o;var a=Object.keys(n),s=function(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(n)),_(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(n);if(0===a.length){if(k(n)){var u=n.name?": "+n.name:"";return e.stylize("[Function"+u+"]","special")}if(b(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(x(n))return e.stylize(Date.prototype.toString.call(n),"date");if(_(n))return f(n)}var l,w="",T=!1,j=["{","}"];(d(n)&&(T=!0,j=["[","]"]),k(n))&&(w=" [Function"+(n.name?": "+n.name:"")+"]");return b(n)&&(w=" "+RegExp.prototype.toString.call(n)),x(n)&&(w=" "+Date.prototype.toUTCString.call(n)),_(n)&&(w=" "+f(n)),0!==a.length||T&&0!=n.length?r<0?b(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special"):(e.seen.push(n),l=T?function(e,t,n,r,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1];return n[0]+t+" "+e.join(", ")+" "+n[1]}(l,w,j)):j[0]+w+j[1]}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,n,r,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),E(r,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=v(n)?c(e,u.value,null):c(e,u.value,n-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),m(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function v(e){return null===e}function y(e){return"number"==typeof e}function g(e){return"string"==typeof e}function m(e){return void 0===e}function b(e){return w(e)&&"[object RegExp]"===T(e)}function w(e){return"object"==typeof e&&null!==e}function x(e){return w(e)&&"[object Date]"===T(e)}function _(e){return w(e)&&("[object Error]"===T(e)||e instanceof Error)}function k(e){return"function"==typeof e}function T(e){return Object.prototype.toString.call(e)}function j(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(n){if(m(o)&&(o=e.env.NODE_DEBUG||""),n=n.toUpperCase(),!a[n])if(new RegExp("\\b"+n+"\\b","i").test(o)){var r=e.pid;a[n]=function(){var e=t.format.apply(t,arguments);console.error("%s %d: %s",n,r,e)}}else a[n]=function(){};return a[n]},t.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=d,t.isBoolean=p,t.isNull=v,t.isNullOrUndefined=function(e){return null==e},t.isNumber=y,t.isString=g,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=m,t.isRegExp=b,t.isObject=w,t.isDate=x,t.isError=_,t.isFunction=k,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=n(77);var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,n;console.log("%s - %s",(e=new Date,n=[j(e.getHours()),j(e.getMinutes()),j(e.getSeconds())].join(":"),[e.getDate(),S[e.getMonth()],n].join(" ")),t.format.apply(t,arguments))},t.inherits=n(7),t._extend=function(e,t){if(!t||!w(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};var O="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function N(e,t){if(!e){var n=new Error("Promise was rejected with a falsy value");n.reason=e,e=n}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(O&&e[O]){var t;if("function"!=typeof(t=e[O]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,O,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,n,r=new Promise(function(e,r){t=e,n=r}),i=[],o=0;o as "+p);throw t.cause=e,t}v(e,n)}}(e)}e.handled={"text/n3":!0,"text/turtle":!0,"application/rdf+xml":!0,"application/xhtml+xml":!0,"text/html":!0,"application/sparql-update":!0,"application/ld+json":!0,"application/nquads":!0,"application/n-quads":!0};function x(){v&&v(null,n)}function _(e,t){e&&v(e,n);try{m.parse(t,k)}catch(e){v(e,n)}}function k(e,t,r){if(e&&v(e,n),t)b.push(t);else{for(var i=0;i: Bad syntax:\n "+i+'\n at: "'+n.slice(r,r+30)+'"'};o=0;var d=t.sym(n+"#query");f.query=d;for(;;){if((a=c.skipSpace(e,o))<0)return f;if(";"===e[a]){if((o=c.skipSpace(e,a+1))<0)return f;a=o}var p=!1;for(s=0;s=e.length&&n())}if(n=n||function(){},!e.length)return n();var r=0;h(e,function(e){t(e,s(a))})},d.forEach=d.each,d.eachSeries=function(e,t,n){if(n=n||function(){},!e.length)return n();var a=0,r=function(){t(e[a],function(t){t?(n(t),n=function(){}):(a+=1,a>=e.length?n():r())})};r()},d.forEachSeries=d.eachSeries,d.eachLimit=function(e,t,n,a){var r=y(t);r.apply(null,[e,n,a])},d.forEachLimit=d.eachLimit;var y=function(e){return function(t,n,a){if(a=a||function(){},!t.length||0>=e)return a();var r=0,o=0,i=0;(function s(){if(r>=t.length)return a();for(;i=t.length?a():s())})})()}},b=function(e){return function(){var t=Array.prototype.slice.call(arguments);return e.apply(null,[d.each].concat(t))}},x=function(e,t){return function(){var n=Array.prototype.slice.call(arguments);return t.apply(null,[y(e)].concat(n))}},_=function(e){return function(){var t=Array.prototype.slice.call(arguments);return e.apply(null,[d.eachSeries].concat(t))}},v=function(e,t,n,a){if(t=f(t,function(e,t){return{index:t,value:e}}),!a)e(t,function(e,t){n(e.value,function(e){t(e)})});else{var r=[];e(t,function(e,t){n(e.value,function(n,a){r[e.index]=a,t(n)})},function(e){a(e,r)})}};d.map=b(v),d.mapSeries=_(v),d.mapLimit=function(e,t,n,a){return w(t)(e,n,a)};var w=function(e){return x(e,v)};d.reduce=function(e,t,n,a){d.eachSeries(e,function(e,a){n(t,e,function(e,n){t=n,a(e)})},function(e){a(e,t)})},d.inject=d.reduce,d.foldl=d.reduce,d.reduceRight=function(e,t,n,a){var r=f(e,function(e){return e}).reverse();d.reduce(r,t,n,a)},d.foldr=d.reduceRight;var k=function(e,t,n,a){var r=[];t=f(t,function(e,t){return{index:t,value:e}}),e(t,function(e,t){n(e.value,function(n){n&&r.push(e),t()})},function(e){a(f(r.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};d.filter=b(k),d.filterSeries=_(k),d.select=d.filter,d.selectSeries=d.filterSeries;var T=function(e,t,n,a){var r=[];t=f(t,function(e,t){return{index:t,value:e}}),e(t,function(e,t){n(e.value,function(n){n||r.push(e),t()})},function(e){a(f(r.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};d.reject=b(T),d.rejectSeries=_(T);var N=function(e,t,n,a){e(t,function(e,t){n(e,function(n){n?(a(e),a=function(){}):t()})},function(e){a()})};d.detect=b(N),d.detectSeries=_(N),d.some=function(e,t,n){d.each(e,function(e,a){t(e,function(e){e&&(n(!0),n=function(){}),a()})},function(e){n(!1)})},d.any=d.some,d.every=function(e,t,n){d.each(e,function(e,a){t(e,function(e){e||(n(!1),n=function(){}),a()})},function(e){n(!0)})},d.all=d.every,d.sortBy=function(e,t,n){d.map(e,function(e,n){t(e,function(t,a){t?n(t):n(null,{value:e,criteria:a})})},function(e,t){if(e)return n(e);var a=function(e,t){var n=e.criteria,a=t.criteria;return na?1:0};n(null,f(t.sort(a),function(e){return e.value}))})},d.auto=function(e,t){t=t||function(){};var n=m(e),a=n.length;if(!a)return t();var r={},s=[],i=function(e){s.unshift(e)},l=function(e){for(var t=0;t=a.length&&(a=a[0]),e){var o={};h(m(r),function(e){o[e]=r[e]}),o[n]=a,t(e,o),t=function(){}}else r[n]=a,d.setImmediate(p)},u=a.slice(0,o(a.length-1))||[],f=function(){return g(u,function(e,t){return e&&r.hasOwnProperty(t)},!0)&&!r.hasOwnProperty(n)};if(f())a[a.length-1](s,r);else{var y=function(){f()&&(l(y),a[a.length-1](s,r))};i(y)}})},d.retry=function(e,t,n){var a=5,r=[];'function'==typeof e&&(n=t,t=e,e=a),e=parseInt(e,10)||a;var o=function(a,o){for(var i=function(e,t){return function(n){e(function(e,a){n(!e||t,{err:e,result:a})},o)}};e;)r.push(i(t,!(e-=1)));d.series(r,function(e,t){t=t[t.length-1],(a||n)(t.err,t.result)})};return n?o():o},d.waterfall=function(e,t){if(t=t||function(){},!c(e)){var n=new Error('First argument to waterfall must be an array of functions');return t(n)}if(!e.length)return t();var a=function(e){return function(n){if(n)t.apply(null,arguments),t=function(){};else{var r=Array.prototype.slice.call(arguments,1),o=e.next();o?r.push(a(o)):r.push(t),d.setImmediate(function(){e.apply(null,r)})}}};a(d.iterator(e))()};var I=function(e,t,n){if(n=n||function(){},c(t))e.map(t,function(e,t){e&&e(function(e){var n=Array.prototype.slice.call(arguments,1);1>=n.length&&(n=n[0]),t.call(null,e,n)})},n);else{var a={};e.each(m(t),function(e,n){t[e](function(t){var r=Array.prototype.slice.call(arguments,1);1>=r.length&&(r=r[0]),a[e]=r,n(t)})},function(e){n(e,a)})}};d.parallel=function(e,t){I({map:d.map,each:d.each},e,t)},d.parallelLimit=function(e,t,n){I({map:w(t),each:y(t)},e,n)},d.series=function(e,t){if(t=t||function(){},c(e))d.mapSeries(e,function(e,t){e&&e(function(e){var n=Array.prototype.slice.call(arguments,1);1>=n.length&&(n=n[0]),t.call(null,e,n)})},t);else{var n={};d.eachSeries(m(e),function(t,a){e[t](function(e){var r=Array.prototype.slice.call(arguments,1);1>=r.length&&(r=r[0]),n[t]=r,a(e)})},function(e){t(e,n)})}},d.iterator=function(e){var t=function(n){var a=function(){return e.length&&e[n].apply(null,arguments),a.next()};return a.next=function(){return n>>1),0<=n(t,e[o])?a=o:r=o-1;return a}function r(e,t,r,o){return e.started||(e.started=!0),c(t)||(t=[t]),0==t.length?d.setImmediate(function(){e.drain&&e.drain()}):void h(t,function(t){var i={data:t,priority:r,callback:'function'==typeof o?o:null};e.tasks.splice(a(e.tasks,i,n)+1,0,i),e.saturated&&e.tasks.length===e.concurrency&&e.saturated(),d.setImmediate(e.process)})};var o=d.queue(e,t);return o.push=function(e,t,n){r(o,e,t,n)},delete o.unshift,o},d.cargo=function(e,t){var n=!1,a=[],r={tasks:a,payload:t,saturated:null,empty:null,drain:null,drained:!0,push:function(e,n){c(e)||(e=[e]),h(e,function(e){a.push({data:e,callback:'function'==typeof n?n:null}),r.drained=!1,r.saturated&&a.length===t&&r.saturated()}),d.setImmediate(r.process)},process:function o(){if(!n){if(0===a.length)return r.drain&&!r.drained&&r.drain(),void(r.drained=!0);var i='number'==typeof t?a.splice(0,t):a.splice(0,a.length),s=f(i,function(e){return e.data});r.empty&&r.empty(),n=!0,e(s,function(){n=!1;var e=arguments;h(i,function(t){t.callback&&t.callback.apply(null,e)}),o()})}},length:function(){return a.length},running:function(){return n}};return r};var j=function(e){return function(t){var n=Array.prototype.slice.call(arguments,1);t.apply(null,n.concat([function(t){var n=Array.prototype.slice.call(arguments,1);'undefined'!=typeof console&&(t?console.error&&console.error(t):console[e]&&h(n,function(t){console[e](t)}))}]))}};d.log=j('log'),d.dir=j('dir'),d.memoize=function(e,t){var n={},a={};t=t||function(e){return e};var r=function(){var r=Array.prototype.slice.call(arguments),o=r.pop(),s=t.apply(null,r);s in n?d.nextTick(function(){o.apply(null,n[s])}):s in a?a[s].push(o):(a[s]=[o],e.apply(null,r.concat([function(){n[s]=arguments;var e=a[s];delete a[s];for(var t=0,r=e.length;t>16,s[d++]=255&i>>8,s[d++]=255&i;return 2===r&&(i=c[e.charCodeAt(p)]<<2|c[e.charCodeAt(p+1)]>>4,s[d++]=255&i),1===r&&(i=c[e.charCodeAt(p)]<<10|c[e.charCodeAt(p+1)]<<4|c[e.charCodeAt(p+2)]>>2,s[d++]=255&i>>8,s[d++]=255&i),s}function d(e){return u[63&e>>18]+u[63&e>>12]+u[63&e>>6]+u[63&e]}function l(e,t,n){for(var a=[],r=t,o;ri?i:o+r));return 1==n?(s=e[t-1],a.push(u[s>>2]+u[63&s<<4]+'==')):2==n&&(s=(e[t-2]<<8)+e[t-1],a.push(u[s>>10]+u[63&s>>4]+u[63&s<<2]+'=')),a.join('')}t.byteLength=r,t.toByteArray=s,t.fromByteArray=p;for(var u=[],c=[],h='undefined'==typeof Uint8Array?Array:Uint8Array,f='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',g=0,i=f.length;g>1,h=-7,f=r?l-1:0,i=r?-1:1,d=t[a+f],s,e;for(f+=i,s=d&(1<<-h)-1,d>>=-h,h+=p;0>=-h,h+=o;0>1,b=23===u?5.960464477539063e-8-6.617444900424222e-24:0,x=p?0:h-1,i=p?1:-1,d=0>r||0===r&&0>1/r?1:0,s,_,m;for(r=o(r),isNaN(r)||r===Infinity?(_=isNaN(r)?1:0,s=g):(s=a(Math.log(r)/Math.LN2),1>r*(m=n(2,-s))&&(s--,m*=2),r+=1<=s+y?b/m:b*n(2,1-y),2<=r*m&&(s++,m/=2),s+y>=g?(_=0,s=g):1<=s+y?(_=(r*m-1)*n(2,u),s+=y):(_=r*n(2,y-1)*n(2,u),s=0));8<=u;t[l+x]=255&_,x+=i,_/=256,u-=8);for(s=s<>>0),a=this.head,s=0;a;)r(a.data,n,s),s+=a.data.length,a=a.next;return n},e}(),i&&i.inspect&&i.inspect.custom&&(e.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+' '+e})},function(e,t){},function(e,t,n){(function(t){function n(e,t){function n(){if(!r){if(a('throwDeprecation'))throw new Error(t);else a('traceDeprecation')?console.trace(t):console.warn(t);r=!0}return e.apply(this,arguments)}if(a('noDeprecation'))return e;var r=!1;return n}function a(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&'true'===(n+'').toLowerCase()}e.exports=n}).call(this,n(3))},function(e,t,n){'use strict';function a(e){return this instanceof a?void r.call(this,e):new a(e)}e.exports=a;var r=n(52),o=n(14);o.inherits=n(7),o.inherits(a,r),a.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){e.exports=n(30)},function(e,t,n){e.exports=n(8)},function(e,t,n){e.exports=n(29).Transform},function(e,t,n){e.exports=n(29).PassThrough},function(e,t){e.exports=function e(t){return t&&'object'==typeof t&&'function'==typeof t.copy&&'function'==typeof t.fill&&'function'==typeof t.readUInt8}},function(e,t,n){'use strict';function a(e){return a='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function e(t){return typeof t}:function e(t){return t&&'function'==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?'symbol':typeof t},a(e)}function r(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function o(e,t){for(var n=0,a;n'):e}function l(e){return'string'==typeof e&&e.match(/^<[^>]*>$/)}function p(e){return'string'==typeof e&&(e.match(/^_:/)||e.match(/^$/))}function u(e){return'string'==typeof e&&e.match(/:$/)}function c(e){return'string'==typeof e&&e.match(/^:|^[^_][^:]*:/)}function h(e){var t=e.split(':');return t[0]}function f(e){var t=e.split(':');return t[1]}function g(e){return l(e)?e.slice(1,e.length-1):e}function m(e){var t=-1===e.indexOf('\'')?null:e.indexOf('\''),o=-1===e.indexOf('"')?null:e.indexOf('"');if(!t&&!o){var i=[,];return i[0]=e,i}var a=[,,],s,d;if(!t||o&&o/g,'> ').replace(/{/g,' { ').replace(/}/g,' } ').replace(/[\t\n\r]/g,' ').replace(/; /g,' ; ').replace(/\. /g,' . ').replace(/, /g,' , '),r.info('New str into spaceDelimit: \n'+e);var t=[],n=e.split(' ');for(var a in n)i(n[a])&&(t=t.concat(n[a]));return t}function b(e){for(var t=e,n=0;n'),'is'===t[n]&&'of'===t[n+2]){t.splice(n,1),t.splice(n+1,1);var a=t[n-1];t[n-1]=t[n+1],t[n+1]=a}return t}function _(e){for(var t=[],o=0;o '+a);var s=h(i),d=g(a);n[s]=d}}return n}function I(e,t,n){r.info('Looking for a close bracket of type '+n+' in '+e);for(var a=0,o=0;oa)return o;return r.error('Statement had no close parenthesis in SPARQL query'),0}function S(e){return this.describe=function(t){return t+' > '+e.toNT()},this.test=function(t){return t.value.match(/[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/)?parseFloat(t.value)>parseFloat(e):t.toNT()>e.toNT()},this}function j(e){return this.describe=function(t){return t+' < '+e.toNT()},this.test=function(t){return t.value.match(/[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/)?parseFloat(t.value)'===e[1]?(r.debug('Constraint added: '+e),t.constraints[e[0]]=new R(e[2])):'<'===e[1]?(r.debug('Constraint added: '+e),t.constraints[e[0]]=new R(e[2])):r.warn('I don\'t know how to handle the constraint: '+e):6===e.length&&'string'==typeof e[0]&&'regexp'===e[0].toLowerCase()&&'('===e[1]&&')'===e[5]&&','===e[3]&&'Variable'===e[4].termType&&'Literal'===e[2].termType&&(r.debug('Constraint added: '+e),t.constraints[e[4]]=new C(e[2].value))}function O(e,t){r.debug('Optional query: '+e+' not yet implemented.');var a=n.formula();E(e,a),t.optional.push(a)}function E(e,t){var n=_(e),a;r.debug('WHERE: '+n);for(var o;w('OPTIONAL',n);)o=w('OPTIONAL',n),r.debug('OPT: '+o+' '+n[o]+' in '+n),'{'!==n[o+1]&&r.warn('Bad optional opening bracket in word '+o),a=I(n.slice(o+2),'{','}'),-1===a?r.error('No matching bracket in word '+o):(O(n.slice(o+2,o+2+a),t),o=w('OPTIONAL',n),a=I(n.slice(o+2),'{','}'),n.splice(o,a+3));for(r.debug('WHERE after optionals: '+n);w('FILTER',n);){var i=w('FILTER',n);'('!==n[i+1]&&r.warn('Bad filter opening bracket in word '+i),a=I(n.slice(i+2),'(',')'),-1===a?r.error('No matching bracket in word '+i):(L(n.slice(i+2,i+2+a),t),i=w('FILTER',n),a=I(n.slice(i+2),'(',')'),n.splice(i,a+3))}r.debug('WHERE after filters and optionals: '+n),D(n,t)}function D(e,t){var n=[,];n[0]=-1;for(var a=n.concat(k('.',e)),o=[],i=0;iF||0>B||F>B)return r.error('Invalid or nonexistent SELECT and WHERE tags in SPARQL query'),!1;if(T(P.slice(F+1,B),A),E(P.slice(B+2,P.length-1),A.pat),t)return A;for(var q in A.pat.statements){var x=A.pat.statements[q];'NamedNode'===x.subject.termType&&n.fetcher&&n.fetcher.lookUpThing(x.subject,'sparql:'+x.subject),'NamedNode'===x.object.termType&&n.fetcher&&n.fetcher.lookUpThing(x.object,'sparql:'+x.object)}return A}var r=n(9),o=n(23).Query;e.exports=a},function(e,t,n){function a(e){return a='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function e(t){return typeof t}:function e(t){return t&&'function'==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?'symbol':typeof t},a(e)}function r(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')}function o(e,t){for(var n=0,a;na;a++)if(r=this.bnodeContext2(t,n,a),null!==r)return r;return this.store.connectedStatements(t,n)}},{key:'mentioned',value:function e(t){return 0!==this.store.statementsMatching(t).length||0!==this.store.statementsMatching(void 0,t).length||0!==this.store.statementsMatching(void 0,void 0,t).length}},{key:'bnodeContext',value:function e(t,n){var a=[];if(t.length){this.cacheIfps();for(var r=0,o;r');var e={noMeta:!0,contentType:'application/sparql-update',body:n};return r.store.fetcher.webOperation('PATCH',t,e)}).then(function(e){if(!e.ok){var r='UpdateManager: update failed for <'+t+'> status='+e.status+', '+e.statusText+'\n for query: '+n;throw console.log(r),new Error(r)}console.log('UpdateManager: update Ok for <'+t+'>'),a(t,e.ok,e.responseText,e)}).catch(function(e){a(t,!1,e.message,e)})}},{key:'update_statement',value:function e(t){if(!t||t.why){var n=this,a=this.statementContext(t);return{statement:t?[t.subject,t.predicate,t.object,t.why]:void 0,statementNT:t?this.anonymizeNT(t):void 0,where:n.contextWhere(a),set_object:function e(t,a){var r=this.where;r+='DELETE DATA { '+this.statementNT+' } ;\n',r+='INSERT DATA { '+this.anonymize(this.statement[0])+' '+this.anonymize(this.statement[1])+' '+this.anonymize(t)+' . }\n',n.fire(this.statement[3].uri,r,a)}}}}},{key:'insert_statement',value:function e(t,n){var a=t instanceof Array?t[0]:t,r=this.contextWhere(this.statementContext(a));if(t instanceof Array){for(var o='',s=0;s 1 different downstream actions')}},{key:'clearUpstreamCount',value:function e(t){var n=this.patchControlFor(t);n.upstreamCount=0}},{key:'getUpdatesVia',value:function e(t){var n=this.store.fetcher.getHeader(t,'updates-via');return n&&n.length?n[0].trim():null}},{key:'addDownstreamChangeListener',value:function e(t,n){var a=this,r=this.patchControlFor(t);r.downstreamChangeListeners||(r.downstreamChangeListeners=[]),r.downstreamChangeListeners.push(n),this.setRefreshHandler(t,function(e){a.reloadAndSync(e)})}},{key:'reloadAndSync',value:function e(t){var n=this.patchControlFor(t),a=this;if(n.reloading)return void console.log(' Already reloading - stop');n.reloading=!0;var r=1e3,o=function e(){console.log('try reload - timeout = '+r),a.reload(a.store,t,function(a,o,s){if(n.reloading=!1,!a)0===s.status?(console.log('Network error refreshing the data. Retrying in '+r/1e3),n.reloading=!0,r*=2,setTimeout(e,r)):console.log('Error '+s.status+'refreshing the data:'+o+'. Stopped'+t);else if(n.downstreamChangeListeners)for(var d=0;d 0'),l.upstreamCount=0,o.requestDownstreamAction(t,r)}}};return l(),!0}},{key:'update',value:function e(t,n,r,o){var d=this;try{var l=this.store,p=t?t instanceof s?t.statements:t instanceof Array?t:[t]:[],u=n?n instanceof s?n.statements:n instanceof Array?n:[n]:[];if(!(p instanceof Array))throw new Error('Type Error '+a(p)+': '+p);if(!(u instanceof Array))throw new Error('Type Error '+a(u)+': '+u);if(0===p.length&&0===u.length)return r(null,!0);var c=p.length?p[0].why:u[0].why;if(!c){var h='Error patching: statement does not specify which document to patch:'+p[0]+', '+u[0];throw console.log(h),new Error(h)}var g=this.patchControlFor(c),m=Date.now(),y=['subject','predicate','object','why'],b=['insert','delete'],x={delete:p,insert:u};b.map(function(e){x[e].map(function(e){if(!c.sameTerm(e.why))throw new Error('update: destination '+c+' inconsistent with delete quad '+e.why);y.map(function(t){if('undefined'==typeof e[t])throw new Error('update: undefined '+t+' of statement.')})})});var _=this.editable(c.uri,l);if(!1===_)throw new Error('Update: Can\'t make changes in uneditable '+c);if(void 0===_){if(o)throw new Error('Update: Loaded '+c+'but stil can\'t figure out what editing protcol it supports.');return console.log('Update: have not loaded '.concat(c,' before: loading now...')),void this.store.fetcher.load(c).then(function(e){d.update(t,n,r,!0)},function(e){throw new Error('Update: Can\'t read '.concat(c,' before patching: ').concat(e))})}if(0<=_.indexOf('SPARQL')){var v=[];p.length&&(v=this.statementArrayBnodes(p)),u.length&&(v=v.concat(this.statementArrayBnodes(u)));var w=this.bnodeContext(v,c),k=this.contextWhere(w),T='';if(k.length){if(p.length){T+='DELETE { ';for(var N=0;N\n')}else throw new Error('Unhandled edit method: \''+_+'\' for '+c)}catch(t){r(void 0,!1,'Exception in update: '+t+'\n'+f.stackString(t))}}},{key:'updateDav',value:function e(t,n,a,r){var o=this.store,s=o.any(t,this.ns.link('request'));if(!s)throw new Error('No record of our HTTP GET request for document: '+t);var d=o.any(s,this.ns.link('response'));if(!d)return null;for(var l=o.the(d,this.ns.httph('content-type')).value,p=o.statementsMatching(void 0,void 0,void 0,t).slice(),u=0,c;uu)throw new Error('Rewriting file: No filename extension: '+t.uri);var c=t.uri.slice(u+1),h=l.CONTENT_TYPE_BY_EXT[c];if(!h)throw new Error('File extension .'+c+' not supported for data write');var g=this.serialize(t.uri,s,h);console.log('Writing back: <<<'+g+'>>>');var m=t.uri.slice(7),y=Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);if(y.initWithPath(m),!y.exists())throw new Error('Rewriting file <'+t.uri+'> but it does not exist!');var b=Components.classes['@mozilla.org/network/file-output-stream;1'].createInstance(Components.interfaces.nsIFileOutputStream);b.init(y,42,parseInt('0666',8),0),b.write(g,g.length),b.close();for(var x=0;x=e.length&&n()}f(e,function(e){t(e,u(i))})},s.forEach=s.each,s.eachSeries=function(e,t,n){if(n=n||function(){},!e.length)return n();var r=0,i=function(){t(e[r],function(t){t?(n(t),n=function(){}):(r+=1)>=e.length?n():i()})};i()},s.forEachSeries=s.eachSeries,s.eachLimit=function(e,t,n,r){p(t).apply(null,[e,n,r])},s.forEachLimit=s.eachLimit;var p=function(e){return function(t,n,r){if(r=r||function(){},!t.length||e<=0)return r();var i=0,o=0,a=0;!function s(){if(i>=t.length)return r();for(;a=t.length?r():s())})}()}},v=function(e){return function(){var t=Array.prototype.slice.call(arguments);return e.apply(null,[s.each].concat(t))}},y=function(e){return function(){var t=Array.prototype.slice.call(arguments);return e.apply(null,[s.eachSeries].concat(t))}},g=function(e,t,n,r){if(t=h(t,function(e,t){return{index:t,value:e}}),r){var i=[];e(t,function(e,t){n(e.value,function(n,r){i[e.index]=r,t(n)})},function(e){r(e,i)})}else e(t,function(e,t){n(e.value,function(e){t(e)})})};s.map=v(g),s.mapSeries=y(g),s.mapLimit=function(e,t,n,r){return m(t)(e,n,r)};var m=function(e){return function(e,t){return function(){var n=Array.prototype.slice.call(arguments);return t.apply(null,[p(e)].concat(n))}}(e,g)};s.reduce=function(e,t,n,r){s.eachSeries(e,function(e,r){n(t,e,function(e,n){t=n,r(e)})},function(e){r(e,t)})},s.inject=s.reduce,s.foldl=s.reduce,s.reduceRight=function(e,t,n,r){var i=h(e,function(e){return e}).reverse();s.reduce(i,t,n,r)},s.foldr=s.reduceRight;var b=function(e,t,n,r){var i=[];e(t=h(t,function(e,t){return{index:t,value:e}}),function(e,t){n(e.value,function(n){n&&i.push(e),t()})},function(e){r(h(i.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};s.filter=v(b),s.filterSeries=y(b),s.select=s.filter,s.selectSeries=s.filterSeries;var w=function(e,t,n,r){var i=[];e(t=h(t,function(e,t){return{index:t,value:e}}),function(e,t){n(e.value,function(n){n||i.push(e),t()})},function(e){r(h(i.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};s.reject=v(w),s.rejectSeries=y(w);var x=function(e,t,n,r){e(t,function(e,t){n(e,function(n){n?(r(e),r=function(){}):t()})},function(e){r()})};s.detect=v(x),s.detectSeries=y(x),s.some=function(e,t,n){s.each(e,function(e,r){t(e,function(e){e&&(n(!0),n=function(){}),r()})},function(e){n(!1)})},s.any=s.some,s.every=function(e,t,n){s.each(e,function(e,r){t(e,function(e){e||(n(!1),n=function(){}),r()})},function(e){n(!0)})},s.all=s.every,s.sortBy=function(e,t,n){s.map(e,function(e,n){t(e,function(t,r){t?n(t):n(null,{value:e,criteria:r})})},function(e,t){if(e)return n(e);n(null,h(t.sort(function(e,t){var n=e.criteria,r=t.criteria;return nr?1:0}),function(e){return e.value}))})},s.auto=function(e,t){t=t||function(){};var n=d(e),r=n.length;if(!r)return t();var i={},o=[],a=function(e){o.unshift(e)},u=function(){r--,f(o.slice(0),function(e){e()})};a(function(){if(!r){var e=t;t=function(){},e(null,i)}}),f(n,function(n){var r=c(e[n])?e[n]:[e[n]],l=function(e){var r=Array.prototype.slice.call(arguments,1);if(r.length<=1&&(r=r[0]),e){var o={};f(d(i),function(e){o[e]=i[e]}),o[n]=r,t(e,o),t=function(){}}else i[n]=r,s.setImmediate(u)},h=r.slice(0,Math.abs(r.length-1))||[],p=function(){return t=function(e,t){return e&&i.hasOwnProperty(t)},r=!0,((e=h).reduce?e.reduce(t,r):(f(e,function(e,n,i){r=t(r,e,n,i)}),r))&&!i.hasOwnProperty(n);var e,t,r};if(p())r[r.length-1](l,i);else{var v=function(){p()&&(!function(e){for(var t=0;t>>1);n(t,e[o])>=0?r=o:i=o-1}return r}(e.tasks,o,n)+1,0,o),e.saturated&&e.tasks.length===e.concurrency&&e.saturated(),s.setImmediate(e.process)})}(r,e,t,i)},delete r.unshift,r},s.cargo=function(e,t){var n=!1,r=[],i={tasks:r,payload:t,saturated:null,empty:null,drain:null,drained:!0,push:function(e,n){c(e)||(e=[e]),f(e,function(e){r.push({data:e,callback:"function"==typeof n?n:null}),i.drained=!1,i.saturated&&r.length===t&&i.saturated()}),s.setImmediate(i.process)},process:function o(){if(!n){if(0===r.length)return i.drain&&!i.drained&&i.drain(),void(i.drained=!0);var a="number"==typeof t?r.splice(0,t):r.splice(0,r.length),s=h(a,function(e){return e.data});i.empty&&i.empty(),n=!0,e(s,function(){n=!1;var e=arguments;f(a,function(t){t.callback&&t.callback.apply(null,e)}),o()})}},length:function(){return r.length},running:function(){return n}};return i};var T=function(e){return function(t){var n=Array.prototype.slice.call(arguments,1);t.apply(null,n.concat([function(t){var n=Array.prototype.slice.call(arguments,1);"undefined"!=typeof console&&(t?console.error&&console.error(t):console[e]&&f(n,function(t){console[e](t)}))}]))}};s.log=T("log"),s.dir=T("dir"),s.memoize=function(e,t){var n={},r={};t=t||function(e){return e};var i=function(){var i=Array.prototype.slice.call(arguments),o=i.pop(),a=t.apply(null,i);a in n?s.nextTick(function(){o.apply(null,n[a])}):a in r?r[a].push(o):(r[a]=[o],e.apply(null,i.concat([function(){n[a]=arguments;var e=r[a];delete r[a];for(var t=0,i=e.length;t2){var r=Array.prototype.slice.call(arguments,2);return n.apply(this,r)}return n};s.applyEach=v(j),s.applyEachSeries=y(j),s.forever=function(e,t){!function n(r){if(r){if(t)return t(r);throw r}e(n)}()},e.exports?e.exports=s:void 0===(i=function(){return s}.apply(t,[]))||(e.exports=i)}()}).call(this,n(4),n(14).setImmediate)},function(e,t,n){(function(e,t){!function(e,n){"use strict";if(!e.setImmediate){var r,i,o,a,s,u=1,l={},c=!1,f=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,"[object process]"==={}.toString.call(e.process)?r=function(e){t.nextTick(function(){p(e)})}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?e.MessageChannel?((o=new MessageChannel).port1.onmessage=function(e){p(e.data)},r=function(e){o.port2.postMessage(e)}):f&&"onreadystatechange"in f.createElement("script")?(i=f.documentElement,r=function(e){var t=f.createElement("script");t.onreadystatechange=function(){p(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):r=function(e){setTimeout(p,0,e)}:(a="setImmediate$"+Math.random()+"$",s=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(a)&&p(+t.data.slice(a.length))},e.addEventListener?e.addEventListener("message",s,!1):e.attachEvent("onmessage",s),r=function(t){e.postMessage(a+t,"*")}),h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n0?r-4:r,f=0;f>16&255,s[u++]=t>>8&255,s[u++]=255&t;2===a&&(t=i[e.charCodeAt(f)]<<2|i[e.charCodeAt(f+1)]>>4,s[u++]=255&t);1===a&&(t=i[e.charCodeAt(f)]<<10|i[e.charCodeAt(f+1)]<<4|i[e.charCodeAt(f+2)]>>2,s[u++]=t>>8&255,s[u++]=255&t);return s},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,o=[],a=0,s=n-i;as?s:a+16383));1===i?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return o.join("")};for(var r=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function c(e,t,n){for(var i,o,a=[],s=t;s>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,r,i){var o,a,s=8*i-r-1,u=(1<>1,c=-7,f=n?i-1:0,h=n?-1:1,d=e[t+f];for(f+=h,o=d&(1<<-c)-1,d>>=-c,c+=s;c>0;o=256*o+e[t+f],f+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=r;c>0;a=256*a+e[t+f],f+=h,c-=8);if(0===o)o=1-l;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,r),o-=l}return(d?-1:1)*a*Math.pow(2,o-r)},t.write=function(e,t,n,r,i,o){var a,s,u,l=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,v=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=c?(s=0,a=c):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[n+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[n+d]=255&a,d+=p,a/=256,l-=8);e[n+d-p]|=128*v}},function(e,t){},function(e,t,n){"use strict";var r=n(20).Buffer,i=n(70);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,i,o=r.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,n=o,i=s,t.copy(n,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(e.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,n){(function(t){function n(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&"true"===String(n).toLowerCase()}e.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}}}).call(this,n(5))},function(e,t,n){"use strict";e.exports=o;var r=n(52),i=n(15);function o(e){if(!(this instanceof o))return new o(e);r.call(this,e)}i.inherits=n(7),i.inherits(o,r),o.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){e.exports=n(30)},function(e,t,n){e.exports=n(8)},function(e,t,n){e.exports=n(29).Transform},function(e,t,n){e.exports=n(29).PassThrough},function(e,t){e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n]*>$/)}function l(e){return"string"==typeof e&&(e.match(/^_:/)||e.match(/^$/))}function c(e){return"string"==typeof e&&e.match(/^:|^[^_][^:]*:/)}function f(e){return e.split(":")[0]}function h(e){return e.split(":")[1]}function d(e){return u(e)?e.slice(1,e.length-1):e}function p(e){e=e.replace(/\(/g," ( ").replace(/\)/g," ) ").replace(//g,"> ").replace(/{/g," { ").replace(/}/g," } ").replace(/[\t\n\r]/g," ").replace(/; /g," ; ").replace(/\. /g," . ").replace(/, /g," , "),r.info("New str into spaceDelimit: \n"+e);var t,n=[],i=e.split(" ");for(var o in i)"string"==typeof(t=i[o])&&t.match(/[^ \n\t]/)&&(n=n.concat(i[o]));return n}function v(e,t){for(var n=0;n"===e[1]?(r.debug("Constraint added: "+e),t.constraints[e[0]]=new m(e[2])):"<"===e[1]?(r.debug("Constraint added: "+e),t.constraints[e[0]]=new m(e[2])):r.warn("I don't know how to handle the constraint: "+e)}function x(e,t){r.debug("Optional query: "+e+" not yet implemented.");var i=n.formula();_(e,i),t.optional.push(i)}function _(e,t){var i,o,p=function(e){for(var t,i=[],o=0;o"):t,s(e[o])?i[o]=a(e[o].slice(1)):l(e[o])?(r.info(e[o]+" was identified as a bnode."),i[o]=n.bnode()):u(e[o])?(r.info(e[o]+" was identified as a symbol."),i[o]=n.sym(d(e[o]))):c(e[o])?(r.info(e[o]+" was identified as a prefixed symbol"),j[f(e[o])]?i[o]=n.sym(e[o]=j[f(e[o])]+h(e[o])):(r.error("SPARQL error: "+e[o]+" with prefix "+f(e[o])+" does not have a correct prefix entry."),i[o]=e[o])):i[o]=e[o]):i[o]=e[o];return i}(e);for(r.debug("WHERE: "+p);v("OPTIONAL",p);)o=v("OPTIONAL",p),r.debug("OPT: "+o+" "+p[o]+" in "+p),"{"!==p[o+1]&&r.warn("Bad optional opening bracket in word "+o),-1===(i=g(p.slice(o+2),"{","}"))?r.error("No matching bracket in word "+o):(x(p.slice(o+2,o+2+i),t),o=v("OPTIONAL",p),i=g(p.slice(o+2),"{","}"),p.splice(o,i+3));for(r.debug("WHERE after optionals: "+p);v("FILTER",p);){var m=v("FILTER",p);"("!==p[m+1]&&r.warn("Bad filter opening bracket in word "+m),-1===(i=g(p.slice(m+2),"(",")"))?r.error("No matching bracket in word "+m):(w(p.slice(m+2,m+2+i),t),m=v("FILTER",p),i=g(p.slice(m+2),"(",")"),p.splice(m,i+3))}r.debug("WHERE after filters and optionals: "+p),function(e,t){var n=new Array(1);n[0]=-1;for(var i=n.concat(y(".",e)),o=[],a=0;a"),"is"===t[n]&&"of"===t[n+2]){t.splice(n,1),t.splice(n+1,1);var r=t[n-1];t[n-1]=t[n+1],t[n+1]=r}return t}(i),r.info("SPARQL Tokens: "+i),i}(e),j=function(e){var t,n=y("PREFIX",e),i=[];for(var o in n){var a=e[n[o]+1],s=e[n[o]+2];if("string"==typeof(t=a)&&t.match(/:$/))if(u(s)){r.info("Prefix found: "+a+" -> "+s);var l=f(a),c=d(s);i[l]=c}else r.error("Invalid SPARQL symbol: "+s);else r.error("Invalid SPARQL prefix: "+a)}return i}(T);j.rdf||(j.rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"),j.rdfs||(j.rdfs="http://www.w3.org/2000/01/rdf-schema#");var S=v("SELECT",T),E=v("WHERE",T);if(S<0||E<0||S>E)return r.error("Invalid or nonexistent SELECT and WHERE tags in SPARQL query"),!1;if(function(e,t){for(var n in r.info("SPARQL vars: "+e),e)if(s(e[n])){r.info("Added "+e[n]+" to query variables from SPARQL");var i=a(e[n].slice(1));t.vars.push(i),i.label=e[n].slice(1)}else r.warn("Incorrect SPARQL variable in SELECT: "+e[n])}(T.slice(S+1,E),k),_(T.slice(E+2,T.length-1),k.pat),t)return k;for(var O in k.pat.statements){var N=k.pat.statements[O];"NamedNode"===N.subject.termType&&n.fetcher&&n.fetcher.lookUpThing(N.subject,"sparql:"+N.subject),"NamedNode"===N.object.termType&&n.fetcher&&n.fetcher.lookUpThing(N.object,"sparql:"+N.object)}return k}},function(e,t,n){function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var n=0;n=0)return"SPARQL";var d=t.each(c,this.ns.httph("ms-author-via"));if(d.length)for(var p=0;p=0)return"SPARQL";if(i.indexOf("DAV")>=0)return"DAV"}var v=t.each(c,this.ns.http("status"));if(v.length)for(var y=0;y");var n={noMeta:!0,contentType:"application/sparql-update",body:t};return r.store.fetcher.webOperation("PATCH",e,n)}).then(function(r){if(!r.ok){var i="UpdateManager: update failed for <"+e+"> status="+r.status+", "+r.statusText+"\n for query: "+t;throw console.log(i),new Error(i)}console.log("UpdateManager: update Ok for <"+e+">"),n(e,r.ok,r.responseText,r)}).catch(function(t){n(e,!1,t.message,t)})}},{key:"update_statement",value:function(e){if(!e||e.why){var t=this,n=this.statementContext(e);return{statement:e?[e.subject,e.predicate,e.object,e.why]:void 0,statementNT:e?this.anonymizeNT(e):void 0,where:t.contextWhere(n),set_object:function(e,n){var r=this.where;r+="DELETE DATA { "+this.statementNT+" } ;\n",r+="INSERT DATA { "+this.anonymize(this.statement[0])+" "+this.anonymize(this.statement[1])+" "+this.anonymize(e)+" . }\n",t.fire(this.statement[3].uri,r,n)}}}}},{key:"insert_statement",value:function(e,t){var n=e instanceof Array?e[0]:e,r=this.contextWhere(this.statementContext(n));if(e instanceof Array){for(var i="",o=0;o 1 different downstream actions")}else n.downstreamAction=t;else t(e)}},{key:"clearUpstreamCount",value:function(e){this.patchControlFor(e).upstreamCount=0}},{key:"getUpdatesVia",value:function(e){var t=this.store.fetcher.getHeader(e,"updates-via");return t&&t.length?t[0].trim():null}},{key:"addDownstreamChangeListener",value:function(e,t){var n=this,r=this.patchControlFor(e);r.downstreamChangeListeners||(r.downstreamChangeListeners=[]),r.downstreamChangeListeners.push(t),this.setRefreshHandler(e,function(e){n.reloadAndSync(e)})}},{key:"reloadAndSync",value:function(e){var t=this.patchControlFor(e),n=this;if(t.reloading)return console.log(" Already reloading - note this load may be out of date"),void(t.outOfDate=!0);t.reloading=!0;var r=1e3;!function i(){console.log("try reload - timeout = "+r),n.reload(n.store,e,function(n,o,a){if(n){if(t.downstreamChangeListeners)for(var s=0;s=0))return void console.log("just an echo: "+l.upstreamCount);console.log("Assume a real downstream change: "+l.upstreamCount+" -> 0"),l.upstreamCount=0,i.requestDownstreamAction(e,r)}}}(),!0}},{key:"update",value:function(e,t,n,i){var a=this;if(!n){var s=this;return new Promise(function(n,r){s.update(e,t,function(e,t,i){t?n():r(new Error(i))})})}try{var u=this.store,l=e?e instanceof o?e.statements:e instanceof Array?e:[e]:[],c=t?t instanceof o?t.statements:t instanceof Array?t:[t]:[];if(!(l instanceof Array))throw new Error("Type Error "+r(l)+": "+l);if(!(c instanceof Array))throw new Error("Type Error "+r(c)+": "+c);if(0===l.length&&0===c.length)return n(null,!0);var f=l.length?l[0].why:c[0].why;if(!f){var d="Error patching: statement does not specify which document to patch:"+l[0]+", "+c[0];throw console.log(d),new Error(d)}var p=this.patchControlFor(f),v=Date.now(),y=["subject","predicate","object","why"],g={delete:l,insert:c};["insert","delete"].map(function(e){g[e].map(function(e){if(!f.sameTerm(e.why))throw new Error("update: destination "+f+" inconsistent with delete quad "+e.why);y.map(function(t){if(void 0===e[t])throw new Error("update: undefined "+t+" of statement.")})})});var m=this.editable(f.uri,u);if(!1===m)throw new Error("Update: Can't make changes in uneditable "+f);if(void 0===m){if(i)throw new Error("Update: Loaded "+f+"but stil can't figure out what editing protcol it supports.");return console.log("Update: have not loaded ".concat(f," before: loading now...")),void this.store.fetcher.load(f).then(function(r){a.update(e,t,n,!0)},function(e){throw new Error("Update: Can't read ".concat(f," before patching: ").concat(e))})}if(m.indexOf("SPARQL")>=0){var b=[];l.length&&(b=this.statementArrayBnodes(l)),c.length&&(b=b.concat(this.statementArrayBnodes(c)));var w=this.bnodeContext(b,f),x=this.contextWhere(w),_="";if(x.length){if(l.length){_+="DELETE { ";for(var k=0;k=0)this.updateDav(f,l,c,n);else{if(!(m.indexOf("LOCALFILE")>=0))throw new Error("Unhandled edit method: '"+m+"' for "+f);try{this.updateLocalFile(f,l,c,n)}catch(e){n(f.uri,!1,"Exception trying to write back file <"+f.uri+">\n")}}}catch(e){n(void 0,!1,"Exception in update: "+e+"\n"+h.stackString(e))}}},{key:"updateDav",value:function(e,t,n,r){var i=this.store,o=i.any(e,this.ns.link("request"));if(!o)throw new Error("No record of our HTTP GET request for document: "+e);var a=i.any(o,this.ns.link("response"));if(!a)return null;for(var s=i.the(a,this.ns.httph("content-type")).value,u=i.statementsMatching(void 0,void 0,void 0,e).slice(),l=0;l>>");var p=e.uri.slice(7),v=Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);if(v.initWithPath(p),!v.exists())throw new Error("Rewriting file <"+e.uri+"> but it does not exist!");var y=Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);y.init(v,42,parseInt("0666",8),0),y.write(d,d.length),y.close();for(var g=0;g \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","/**\n*\n* UTF-8 data encode / decode\n* http://www.webtoolkit.info/\n*\n**/\nconst Uri = require('./uri')\nconst ArrayIndexOf = require('./util').ArrayIndexOf\n\nvar N3Parser = (function () {\n\nfunction hexify (str) { // also used in parser\n return encodeURI(str);\n}\n\nvar Utf8 = {\n // public method for url encoding\n encode : function (string) {\n string = string.replace(/\\r\\n/g,\"\\n\");\n var utftext = \"\";\n\n for (var n = 0; n < string.length; n++) {\n\n var c = string.charCodeAt(n);\n\n if (c < 128) {\n utftext += String.fromCharCode(c);\n }\n else if((c > 127) && (c < 2048)) {\n utftext += String.fromCharCode((c >> 6) | 192);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n else {\n utftext += String.fromCharCode((c >> 12) | 224);\n utftext += String.fromCharCode(((c >> 6) & 63) | 128);\n utftext += String.fromCharCode((c & 63) | 128);\n }\n\n }\n\n return utftext;\n },\n // public method for url decoding\n decode : function (utftext) {\n var string = \"\";\n var i = 0;\n\n while ( i < utftext.length ) {\n\n var c = utftext.charCodeAt(i);\n if (c < 128) {\n string += String.fromCharCode(c);\n i++;\n }\n else if((c > 191) && (c < 224)) {\n string += String.fromCharCode(((c & 31) << 6)\n | (utftext.charCodeAt(i+1) & 63));\n i += 2;\n }\n else {\n string += String.fromCharCode(((c & 15) << 12)\n | ((utftext.charCodeAt(i+1) & 63) << 6)\n | (utftext.charCodeAt(i+2) & 63));\n i += 3;\n }\n }\n return string;\n }\n}// Things we need to define to make converted pythn code work in js\n// environment of $rdf\n\nvar RDFSink_forSomeSym = \"http://www.w3.org/2000/10/swap/log#forSome\";\nvar RDFSink_forAllSym = \"http://www.w3.org/2000/10/swap/log#forAll\";\nvar Logic_NS = \"http://www.w3.org/2000/10/swap/log#\";\n\n// pyjs seems to reference runtime library which I didn't find\n\nvar pyjslib_Tuple = function(theList) { return theList };\n\nvar pyjslib_List = function(theList) { return theList };\n\nvar pyjslib_Dict = function(listOfPairs) {\n if (listOfPairs.length > 0)\n\tthrow \"missing.js: oops nnonempty dict not imp\";\n return [];\n}\n\nvar pyjslib_len = function(s) { return s.length }\n\nvar pyjslib_slice = function(str, i, j) {\n if (typeof str.slice == 'undefined')\n throw '@@ mising.js: No .slice function for '+str+' of type '+(typeof str)\n if ((typeof j == 'undefined') || (j ==null)) return str.slice(i);\n return str.slice(i, j) // @ exactly the same spec?\n}\nvar StopIteration = Error('dummy error stop iteration');\n\nvar pyjslib_Iterator = function(theList) {\n this.last = 0;\n this.li = theList;\n this.next = function() {\n\tif (this.last == this.li.length) throw StopIteration;\n\treturn this.li[this.last++];\n }\n return this;\n};\n\nvar ord = function(str) {\n return str.charCodeAt(0)\n}\n\nvar string_find = function(str, s) {\n return str.indexOf(s)\n}\n\nvar assertFudge = function(condition, desc) {\n if (condition) return;\n if (desc) throw \"python Assertion failed: \"+desc;\n throw \"(python) Assertion failed.\";\n}\n\n\nvar stringFromCharCode = function(uesc) {\n return String.fromCharCode(uesc);\n}\n\n\nString.prototype.encode = function(encoding) {\n if (encoding != 'utf-8') throw \"UTF8_converter: can only do utf-8\"\n return Utf8.encode(this);\n}\nString.prototype.decode = function(encoding) {\n if (encoding != 'utf-8') throw \"UTF8_converter: can only do utf-8\"\n //return Utf8.decode(this);\n return this;\n}\n\n\n\nvar uripath_join = function(base, given) {\n return Uri.join(given, base) // sad but true\n}\n\nvar becauseSubexpression = null; // No reason needed\nvar diag_tracking = 0;\nvar diag_chatty_flag = 0;\nvar diag_progress = function(str) { /*$rdf.log.debug(str);*/ }\n\n// why_BecauseOfData = function(doc, reason) { return doc };\n\n\nvar RDF_type_URI = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\";\nvar DAML_sameAs_URI = \"http://www.w3.org/2002/07/owl#sameAs\";\n\n/*\nfunction SyntaxError(details) {\n return new __SyntaxError(details);\n}\n*/\n\nfunction __SyntaxError(details) {\n this.details = details\n}\n\n/*\n\n$Id: n3parser.js 14561 2008-02-23 06:37:26Z kennyluck $\n\nHAND EDITED FOR CONVERSION TO JAVASCRIPT\n\nThis module implements a Nptation3 parser, and the final\npart of a notation3 serializer.\n\nSee also:\n\nNotation 3\nhttp://www.w3.org/DesignIssues/Notation3\n\nClosed World Machine - and RDF Processor\nhttp://www.w3.org/2000/10/swap/cwm\n\nTo DO: See also \"@@\" in comments\n\n- Clean up interfaces\n______________________________________________\n\nModule originally by Dan Connolly, includeing notation3\nparser and RDF generator. TimBL added RDF stream model\nand N3 generation, replaced stream model with use\nof common store/formula API. Yosi Scharf developped\nthe module, including tests and test harness.\n\n*/\n\nvar ADDED_HASH = \"#\";\nvar LOG_implies_URI = \"http://www.w3.org/2000/10/swap/log#implies\";\nvar INTEGER_DATATYPE = \"http://www.w3.org/2001/XMLSchema#integer\";\nvar FLOAT_DATATYPE = \"http://www.w3.org/2001/XMLSchema#double\";\nvar DECIMAL_DATATYPE = \"http://www.w3.org/2001/XMLSchema#decimal\";\nvar DATE_DATATYPE = \"http://www.w3.org/2001/XMLSchema#date\";\nvar DATETIME_DATATYPE = \"http://www.w3.org/2001/XMLSchema#dateTime\";\nvar BOOLEAN_DATATYPE = \"http://www.w3.org/2001/XMLSchema#boolean\";\nvar option_noregen = 0;\nvar _notQNameChars = \"\\t\\r\\n !\\\"#$%&'()*.,+/;<=>?@[\\\\]^`{|}~\";\nvar _notNameChars = ( _notQNameChars + \":\" ) ;\nvar _rdfns = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\";\nvar N3CommentCharacter = \"#\";\nvar eol = new RegExp(\"^[ \\\\t]*(#[^\\\\n]*)?\\\\r?\\\\n\", 'g');\nvar eof = new RegExp(\"^[ \\\\t]*(#[^\\\\n]*)?$\", 'g');\nvar ws = new RegExp(\"^[ \\\\t]*\", 'g');\nvar signed_integer = new RegExp(\"^[-+]?[0-9]+\", 'g');\nvar number_syntax = new RegExp(\"^([-+]?[0-9]+)(\\\\.[0-9]+)?(e[-+]?[0-9]+)?\", 'g');\nvar 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?');\n\nvar digitstring = new RegExp(\"^[0-9]+\", 'g');\nvar interesting = new RegExp(\"[\\\\\\\\\\\\r\\\\n\\\\\\\"]\", 'g');\nvar langcode = new RegExp(\"^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\", 'g');\nfunction SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) {\n return new __SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why);\n}\nfunction __SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) {\n if (typeof openFormula == 'undefined') openFormula=null;\n if (typeof thisDoc == 'undefined') thisDoc=\"\";\n if (typeof baseURI == 'undefined') baseURI=null;\n if (typeof genPrefix == 'undefined') genPrefix=\"\";\n if (typeof metaURI == 'undefined') metaURI=null;\n if (typeof flags == 'undefined') flags=\"\";\n if (typeof why == 'undefined') why=null;\n /*\n note: namespace names should *not* end in #;\n the # will get added during qname processing */\n\n this._bindings = new pyjslib_Dict([]);\n this._flags = flags;\n if ((thisDoc != \"\")) {\n assertFudge((thisDoc.indexOf(\":\") >= 0), ( \"Document URI not absolute: \" + thisDoc ) );\n this._bindings[\"\"] = ( ( thisDoc + \"#\" ) );\n }\n this._store = store;\n if (genPrefix) {\n store.setGenPrefix(genPrefix);\n }\n this._thisDoc = thisDoc;\n this.source = store.sym(thisDoc);\n this.lines = 0;\n this.statementCount = 0;\n this.startOfLine = 0;\n this.previousLine = 0;\n this._genPrefix = genPrefix;\n this.keywords = new pyjslib_List([\"a\", \"this\", \"bind\", \"has\", \"is\", \"of\", \"true\", \"false\"]);\n this.keywordsSet = 0;\n this._anonymousNodes = new pyjslib_Dict([]);\n this._variables = new pyjslib_Dict([]);\n this._parentVariables = new pyjslib_Dict([]);\n this._reason = why;\n this._reason2 = null;\n if (diag_tracking) {\n this._reason2 = why_BecauseOfData(store.sym(thisDoc), this._reason);\n }\n if (baseURI) {\n this._baseURI = baseURI;\n }\n else {\n if (thisDoc) {\n this._baseURI = thisDoc;\n }\n else {\n this._baseURI = null;\n }\n }\n assertFudge(!(this._baseURI) || (this._baseURI.indexOf(\":\") >= 0));\n if (!(this._genPrefix)) {\n if (this._thisDoc) {\n this._genPrefix = ( this._thisDoc + \"#_g\" ) ;\n }\n else {\n this._genPrefix = RDFSink_uniqueURI();\n }\n }\n if ((openFormula == null)) {\n if (this._thisDoc) {\n this._formula = store.formula( ( thisDoc + \"#_formula\" ) );\n }\n else {\n this._formula = store.formula();\n }\n }\n else {\n this._formula = openFormula;\n }\n this._context = this._formula;\n this._parentContext = null;\n}\n__SinkParser.prototype.here = function(i) {\n return ( ( ( ( this._genPrefix + \"_L\" ) + this.lines ) + \"C\" ) + ( ( i - this.startOfLine ) + 1 ) ) ;\n};\n__SinkParser.prototype.formula = function() {\n return this._formula;\n};\n__SinkParser.prototype.loadStream = function(stream) {\n return this.loadBuf(stream.read());\n};\n__SinkParser.prototype.loadBuf = function(buf) {\n /*\n Parses a buffer and returns its top level formula*/\n\n this.startDoc();\n this.feed(buf);\n return this.endDoc();\n};\n__SinkParser.prototype.feed = function(octets) {\n /*\n Feed an octet stream tothe parser\n\n if BadSyntax is raised, the string\n passed in the exception object is the\n remainder after any statements have been parsed.\n So if there is more data to feed to the\n parser, it should be straightforward to recover.*/\n\n var str = octets.decode(\"utf-8\");\n var i = 0;\n while ((i >= 0)) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return;\n }\n var i = this.directiveOrStatement(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected directive or statement\");\n }\n }\n};\n__SinkParser.prototype.directiveOrStatement = function(str, h) {\n var i = this.skipSpace(str, h);\n if ((i < 0)) {\n return i;\n }\n var j = this.directive(str, i);\n if ((j >= 0)) {\n return this.checkDot(str, j);\n }\n var j = this.statement(str, i);\n if ((j >= 0)) {\n return this.checkDot(str, j);\n }\n return j;\n};\n__SinkParser.prototype.tok = function(tok, str, i) {\n /*\n Check for keyword. Space must have been stripped on entry and\n we must not be at end of file.*/\n var whitespace = \"\\t\\n\\v\\f\\r \";\n if ((pyjslib_slice(str, i, ( i + 1 ) ) == \"@\")) {\n var i = ( i + 1 ) ;\n }\n else {\n if ((ArrayIndexOf(this.keywords,tok) < 0)) {\n return -1;\n }\n }\n var k = ( i + pyjslib_len(tok) ) ;\n if ((pyjslib_slice(str, i, k) == tok) && (_notQNameChars.indexOf(str.charAt(k)) >= 0)) {\n return k;\n }\n else {\n return -1;\n }\n};\n__SinkParser.prototype.directive = function(str, i) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var res = new pyjslib_List([]);\n var j = this.tok(\"bind\", str, i);\n if ((j > 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"keyword bind is obsolete: use @prefix\");\n }\n var j = this.tok(\"keywords\", str, i);\n if ((j > 0)) {\n var i = this.commaSeparatedList(str, j, res, false);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"'@keywords' needs comma separated list of words\");\n }\n this.setKeywords(pyjslib_slice(res, null, null));\n if ((diag_chatty_flag > 80)) {\n diag_progress(\"Keywords \", this.keywords);\n }\n return i;\n }\n var j = this.tok(\"forAll\", str, i);\n if ((j > 0)) {\n var i = this.commaSeparatedList(str, j, res, true);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Bad variable list after @forAll\");\n }\n\n var __x = new pyjslib_Iterator(res);\n try {\n while (true) {\n var x = __x.next();\n\n\n if (ArrayIndexOf(this._variables,x) < 0 || (ArrayIndexOf(this._parentVariables,x) >= 0)) {\n this._variables[x] = ( this._context.newUniversal(x));\n }\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n return i;\n }\n var j = this.tok(\"forSome\", str, i);\n if ((j > 0)) {\n var i = this.commaSeparatedList(str, j, res, this.uri_ref2);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Bad variable list after @forSome\");\n }\n\n var __x = new pyjslib_Iterator(res);\n try {\n while (true) {\n var x = __x.next();\n\n\n this._context.declareExistential(x);\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n return i;\n }\n var j = this.tok(\"prefix\", str, i);\n if ((j >= 0)) {\n var t = new pyjslib_List([]);\n var i = this.qname(str, j, t);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected qname after @prefix\");\n }\n var j = this.uri_ref2(str, i, t);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected after @prefix _qname_\");\n }\n var ns = t[1].uri;\n if (this._baseURI) {\n var ns = uripath_join(this._baseURI, ns);\n }\n else {\n assertFudge((ns.indexOf(\":\") >= 0), \"With no base URI, cannot handle relative URI for NS\");\n }\n assertFudge((ns.indexOf(\":\") >= 0));\n this._bindings[t[0][0]] = ( ns);\n\n this.bind(t[0][0], hexify(ns));\n return j;\n }\n var j = this.tok(\"base\", str, i);\n if ((j >= 0)) {\n var t = new pyjslib_List([]);\n var i = this.uri_ref2(str, j, t);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected after @base \");\n }\n var ns = t[0].uri;\n if (this._baseURI) {\n var ns = uripath_join(this._baseURI, ns);\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, j, ( ( \"With no previous base URI, cannot use relative URI in @base <\" + ns ) + \">\" ) );\n }\n assertFudge((ns.indexOf(\":\") >= 0));\n this._baseURI = ns;\n return i;\n }\n return -1;\n};\n__SinkParser.prototype.bind = function(qn, uri) {\n if ((qn == \"\")) {\n }\n else {\n this._store.setPrefixForURI(qn, uri);\n }\n};\n__SinkParser.prototype.setKeywords = function(k) {\n /*\n Takes a list of strings*/\n\n if ((k == null)) {\n this.keywordsSet = 0;\n }\n else {\n this.keywords = k;\n this.keywordsSet = 1;\n }\n};\n__SinkParser.prototype.startDoc = function() {\n};\n__SinkParser.prototype.endDoc = function() {\n /*\n Signal end of document and stop parsing. returns formula*/\n\n return this._formula;\n};\n__SinkParser.prototype.makeStatement = function(quad) {\n quad[0].add(quad[2], quad[1], quad[3], this.source);\n this.statementCount += 1;\n};\n__SinkParser.prototype.statement = function(str, i) {\n var r = new pyjslib_List([]);\n var i = this.object(str, i, r);\n if ((i < 0)) {\n return i;\n }\n var j = this.property_list(str, i, r[0]);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected propertylist\");\n }\n return j;\n};\n__SinkParser.prototype.subject = function(str, i, res) {\n return this.item(str, i, res);\n};\n__SinkParser.prototype.verb = function(str, i, res) {\n /*\n has _prop_\n is _prop_ of\n a\n =\n _prop_\n >- prop ->\n <- prop -<\n _operator_*/\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var r = new pyjslib_List([]);\n var j = this.tok(\"has\", str, i);\n if ((j >= 0)) {\n var i = this.prop(str, j, r);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected property after 'has'\");\n }\n res.push(new pyjslib_Tuple([\"->\", r[0]]));\n return i;\n }\n var j = this.tok(\"is\", str, i);\n if ((j >= 0)) {\n var i = this.prop(str, j, r);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected after 'is'\");\n }\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"End of file found, expected property after 'is'\");\n return j;\n }\n var i = j;\n var j = this.tok(\"of\", str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected 'of' after 'is' \");\n }\n res.push(new pyjslib_Tuple([\"<-\", r[0]]));\n return j;\n }\n var j = this.tok(\"a\", str, i);\n if ((j >= 0)) {\n res.push(new pyjslib_Tuple([\"->\", this._store.sym(RDF_type_URI)]));\n return j;\n }\n if ((pyjslib_slice(str, i, ( i + 2 ) ) == \"<=\")) {\n res.push(new pyjslib_Tuple([\"<-\", this._store.sym( ( Logic_NS + \"implies\" ) )]));\n return ( i + 2 ) ;\n }\n if ((pyjslib_slice(str, i, ( i + 1 ) ) == \"=\")) {\n if ((pyjslib_slice(str, ( i + 1 ) , ( i + 2 ) ) == \">\")) {\n res.push(new pyjslib_Tuple([\"->\", this._store.sym( ( Logic_NS + \"implies\" ) )]));\n return ( i + 2 ) ;\n }\n res.push(new pyjslib_Tuple([\"->\", this._store.sym(DAML_sameAs_URI)]));\n return ( i + 1 ) ;\n }\n if ((pyjslib_slice(str, i, ( i + 2 ) ) == \":=\")) {\n res.push(new pyjslib_Tuple([\"->\", ( Logic_NS + \"becomes\" ) ]));\n return ( i + 2 ) ;\n }\n var j = this.prop(str, i, r);\n if ((j >= 0)) {\n res.push(new pyjslib_Tuple([\"->\", r[0]]));\n return j;\n }\n if ((pyjslib_slice(str, i, ( i + 2 ) ) == \">-\") || (pyjslib_slice(str, i, ( i + 2 ) ) == \"<-\")) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \">- ... -> syntax is obsolete.\");\n }\n return -1;\n};\n__SinkParser.prototype.prop = function(str, i, res) {\n return this.item(str, i, res);\n};\n__SinkParser.prototype.item = function(str, i, res) {\n return this.path(str, i, res);\n};\n__SinkParser.prototype.blankNode = function(uri) {\n return this._context.bnode(uri, this._reason2);\n};\n__SinkParser.prototype.path = function(str, i, res) {\n /*\n Parse the path production.\n */\n\n var j = this.nodeOrLiteral(str, i, res);\n if ((j < 0)) {\n return j;\n }\n while ((\"!^.\".indexOf(pyjslib_slice(str, j, ( j + 1 ) )) >= 0)) {\n var ch = pyjslib_slice(str, j, ( j + 1 ) );\n if ((ch == \".\")) {\n var ahead = pyjslib_slice(str, ( j + 1 ) , ( j + 2 ) );\n if (!(ahead) || (_notNameChars.indexOf(ahead) >= 0) && (\":?<[{(\".indexOf(ahead) < 0)) {\n break;\n }\n }\n var subj = res.pop();\n var obj = this.blankNode(this.here(j));\n var j = this.node(str, ( j + 1 ) , res);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"EOF found in middle of path syntax\");\n }\n var pred = res.pop();\n if ((ch == \"^\")) {\n this.makeStatement(new pyjslib_Tuple([this._context, pred, obj, subj]));\n }\n else {\n this.makeStatement(new pyjslib_Tuple([this._context, pred, subj, obj]));\n }\n res.push(obj);\n }\n return j;\n};\n__SinkParser.prototype.anonymousNode = function(ln) {\n /*\n Remember or generate a term for one of these _: anonymous nodes*/\n\n var term = this._anonymousNodes[ln];\n if (term) {\n return term;\n }\n var term = this._store.bnode(ln);\n // var term = this._store.bnode(this._context, this._reason2); eh?\n this._anonymousNodes[ln] = ( term);\n return term;\n};\n__SinkParser.prototype.node = function(str, i, res, subjectAlready) {\n if (typeof subjectAlready == 'undefined') subjectAlready=null;\n /*\n Parse the production.\n Space is now skipped once at the beginning\n instead of in multipe calls to self.skipSpace().\n */\n\n var subj = subjectAlready;\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var i = j;\n var ch = pyjslib_slice(str, i, ( i + 1 ) );\n if ((ch == \"[\")) {\n var bnodeID = this.here(i);\n var j = this.skipSpace(str, ( i + 1 ) );\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF after '['\");\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) == \"=\")) {\n var i = ( j + 1 ) ;\n var objs = new pyjslib_List([]);\n var j = this.objectList(str, i, objs);\n\n if ((j >= 0)) {\n var subj = objs[0];\n if ((pyjslib_len(objs) > 1)) {\n\n var __obj = new pyjslib_Iterator(objs);\n try {\n while (true) {\n var obj = __obj.next();\n\n\n this.makeStatement(new pyjslib_Tuple([this._context, this._store.sym(DAML_sameAs_URI), subj, obj]));\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n }\n var j = this.skipSpace(str, j);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF when objectList expected after [ = \");\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) == \";\")) {\n var j = ( j + 1 ) ;\n }\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"objectList expected after [= \");\n }\n }\n if ((subj == null)) {\n var subj = this.blankNode(bnodeID);\n }\n var i = this.property_list(str, j, subj);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"property_list expected\");\n }\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF when ']' expected after [ \");\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) != \"]\")) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"']' expected\");\n }\n res.push(subj);\n return ( j + 1 ) ;\n }\n if ((ch == \"{\")) {\n var ch2 = pyjslib_slice(str, ( i + 1 ) , ( i + 2 ) );\n if ((ch2 == \"$\")) {\n i += 1;\n var j = ( i + 1 ) ;\n var mylist = new pyjslib_List([]);\n var first_run = true;\n while (1) {\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"needed '$}', found end.\");\n }\n if ((pyjslib_slice(str, i, ( i + 2 ) ) == \"$}\")) {\n var j = ( i + 2 ) ;\n break;\n }\n if (!(first_run)) {\n if ((pyjslib_slice(str, i, ( i + 1 ) ) == \",\")) {\n i += 1;\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected: ','\");\n }\n }\n else {\n var first_run = false;\n }\n var item = new pyjslib_List([]);\n var j = this.item(str, i, item);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected item in set or '$}'\");\n }\n mylist.push(item[0]);\n }\n res.push(this._store.newSet(mylist, this._context));\n return j;\n }\n else {\n var j = ( i + 1 ) ;\n var oldParentContext = this._parentContext;\n this._parentContext = this._context;\n var parentAnonymousNodes = this._anonymousNodes;\n var grandParentVariables = this._parentVariables;\n this._parentVariables = this._variables;\n this._anonymousNodes = new pyjslib_Dict([]);\n this._variables = this._variables.slice();\n var reason2 = this._reason2;\n this._reason2 = becauseSubexpression;\n if ((subj == null)) {\n var subj = this._store.formula();\n }\n this._context = subj;\n while (1) {\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"needed '}', found end.\");\n }\n if ((pyjslib_slice(str, i, ( i + 1 ) ) == \"}\")) {\n var j = ( i + 1 ) ;\n break;\n }\n var j = this.directiveOrStatement(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected statement or '}'\");\n }\n }\n this._anonymousNodes = parentAnonymousNodes;\n this._variables = this._parentVariables;\n this._parentVariables = grandParentVariables;\n this._context = this._parentContext;\n this._reason2 = reason2;\n this._parentContext = oldParentContext;\n res.push(subj.close());\n return j;\n }\n }\n if ((ch == \"(\")) {\n var thing_type = this._store.list;\n var ch2 = pyjslib_slice(str, ( i + 1 ) , ( i + 2 ) );\n if ((ch2 == \"$\")) {\n var thing_type = this._store.newSet;\n i += 1;\n }\n var j = ( i + 1 ) ;\n var mylist = new pyjslib_List([]);\n while (1) {\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"needed ')', found end.\");\n }\n if ((pyjslib_slice(str, i, ( i + 1 ) ) == \")\")) {\n var j = ( i + 1 ) ;\n break;\n }\n var item = new pyjslib_List([]);\n var j = this.item(str, i, item);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"expected item in list or ')'\");\n }\n mylist.push(item[0]);\n }\n res.push(thing_type(mylist, this._context));\n return j;\n }\n var j = this.tok(\"this\", str, i);\n if ((j >= 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords.\");\n res.push(this._context);\n return j;\n }\n var j = this.tok(\"true\", str, i);\n if ((j >= 0)) {\n res.push(true);\n return j;\n }\n var j = this.tok(\"false\", str, i);\n if ((j >= 0)) {\n res.push(false);\n return j;\n }\n if ((subj == null)) {\n var j = this.uri_ref2(str, i, res);\n if ((j >= 0)) {\n return j;\n }\n }\n return -1;\n};\n__SinkParser.prototype.property_list = function(str, i, subj) {\n /*\n Parse property list\n Leaves the terminating punctuation in the buffer\n */\n\n while (1) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF found when expected verb in property list\");\n return j;\n }\n if ((pyjslib_slice(str, j, ( j + 2 ) ) == \":-\")) {\n var i = ( j + 2 ) ;\n var res = new pyjslib_List([]);\n var j = this.node(str, i, res, subj);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"bad {} or () or [] node after :- \");\n }\n var i = j;\n continue;\n }\n var i = j;\n var v = new pyjslib_List([]);\n var j = this.verb(str, i, v);\n if ((j <= 0)) {\n return i;\n }\n var objs = new pyjslib_List([]);\n var i = this.objectList(str, j, objs);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"objectList expected\");\n }\n\n var __obj = new pyjslib_Iterator(objs);\n try {\n while (true) {\n var obj = __obj.next();\n\n\n var pairFudge = v[0];\n var dir = pairFudge[0];\n var sym = pairFudge[1];\n if ((dir == \"->\")) {\n this.makeStatement(new pyjslib_Tuple([this._context, sym, subj, obj]));\n }\n else {\n this.makeStatement(new pyjslib_Tuple([this._context, sym, obj, subj]));\n }\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"EOF found in list of objects\");\n return j;\n }\n if ((pyjslib_slice(str, i, ( i + 1 ) ) != \";\")) {\n return i;\n }\n var i = ( i + 1 ) ;\n }\n};\n__SinkParser.prototype.commaSeparatedList = function(str, j, res, ofUris) {\n /*\n return value: -1 bad syntax; >1 new position in str\n res has things found appended\n\n Used to use a final value of the function to be called, e.g. this.bareWord\n but passing the function didn't work fo js converion pyjs\n */\n\n var i = this.skipSpace(str, j);\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"EOF found expecting comma sep list\");\n return i;\n }\n if ((str.charAt(i) == \".\")) {\n return j;\n }\n if (ofUris) {\n var i = this.uri_ref2(str, i, res);\n }\n else {\n var i = this.bareWord(str, i, res);\n }\n if ((i < 0)) {\n return -1;\n }\n while (1) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n var ch = pyjslib_slice(str, j, ( j + 1 ) );\n if ((ch != \",\")) {\n if ((ch != \".\")) {\n return -1;\n }\n return j;\n }\n if (ofUris) {\n var i = this.uri_ref2(str, ( j + 1 ) , res);\n }\n else {\n var i = this.bareWord(str, ( j + 1 ) , res);\n }\n if ((i < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"bad list content\");\n return i;\n }\n }\n};\n__SinkParser.prototype.objectList = function(str, i, res) {\n var i = this.object(str, i, res);\n if ((i < 0)) {\n return -1;\n }\n while (1) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"EOF found after object\");\n return j;\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) != \",\")) {\n return j;\n }\n var i = this.object(str, ( j + 1 ) , res);\n if ((i < 0)) {\n return i;\n }\n }\n};\n__SinkParser.prototype.checkDot = function(str, i) {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return j;\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) == \".\")) {\n return ( j + 1 ) ;\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) == \"}\")) {\n return j;\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) == \"]\")) {\n return j;\n }\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"expected '.' or '}' or ']' at end of statement\");\n return i;\n};\n__SinkParser.prototype.uri_ref2 = function(str, i, res) {\n /*\n Generate uri from n3 representation.\n\n Note that the RDF convention of directly concatenating\n NS and local name is now used though I prefer inserting a '#'\n to make the namesapces look more like what XML folks expect.\n */\n\n var qn = new pyjslib_List([]);\n var j = this.qname(str, i, qn);\n if ((j >= 0)) {\n var pairFudge = qn[0];\n var pfx = pairFudge[0];\n var ln = pairFudge[1];\n if ((pfx == null)) {\n assertFudge(0, \"not used?\");\n var ns = ( this._baseURI + ADDED_HASH ) ;\n }\n else {\n var ns = this._bindings[pfx];\n if (!(ns)) {\n if ((pfx == \"_\")) {\n res.push(this.anonymousNode(ln));\n return j;\n }\n throw BadSyntax(this._thisDoc, this.lines, str, i, ( ( \"Prefix \" + pfx ) + \" not bound.\" ) );\n }\n }\n var symb = this._store.sym( ( ns + ln ) );\n if ((ArrayIndexOf(this._variables, symb) >= 0)) {\n res.push(this._variables[symb]);\n }\n else {\n res.push(symb);\n }\n return j;\n }\n var i = this.skipSpace(str, i);\n if ((i < 0)) {\n return -1;\n }\n if ((str.charAt(i) == \"?\")) {\n var v = new pyjslib_List([]);\n var j = this.variable(str, i, v);\n if ((j > 0)) {\n res.push(v[0]);\n return j;\n }\n return -1;\n }\n else if ((str.charAt(i) == \"<\")) {\n var i = ( i + 1 ) ;\n var st = i;\n while ((i < pyjslib_len(str))) {\n if ((str.charAt(i) == \">\")) {\n var uref = pyjslib_slice(str, st, i);\n if (this._baseURI) {\n var uref = uripath_join(this._baseURI, uref);\n }\n else {\n assertFudge((uref.indexOf(\":\") >= 0), \"With no base URI, cannot deal with relative URIs\");\n }\n if ((pyjslib_slice(str, ( i - 1 ) , i) == \"#\") && !((pyjslib_slice(uref, -1, null) == \"#\"))) {\n var uref = ( uref + \"#\" ) ;\n }\n var symb = this._store.sym(uref);\n if ((ArrayIndexOf(this._variables,symb) >= 0)) {\n res.push(this._variables[symb]);\n }\n else {\n res.push(symb);\n }\n return ( i + 1 ) ;\n }\n var i = ( i + 1 ) ;\n }\n throw BadSyntax(this._thisDoc, this.lines, str, j, \"unterminated URI reference\");\n }\n else if (this.keywordsSet) {\n var v = new pyjslib_List([]);\n var j = this.bareWord(str, i, v);\n if ((j < 0)) {\n return -1;\n }\n if ((ArrayIndexOf(this.keywords, v[0]) >= 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, i, ( ( \"Keyword \\\"\" + v[0] ) + \"\\\" not allowed here.\" ) );\n }\n res.push(this._store.sym( ( this._bindings[\"\"] + v[0] ) ));\n return j;\n }\n else {\n return -1;\n }\n};\n__SinkParser.prototype.skipSpace = function(str, i) {\n /*\n Skip white space, newlines and comments.\n return -1 if EOF, else position of first non-ws character*/\n\n var whitespace = ' \\n\\r\\t\\f\\x0b\\xa0\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u200b\\u2028\\u2029\\u3000';\n for (var j = (i ? i : 0); j < str.length; j++) {\n var ch = str.charAt(j);\n // console.log(\" skipspace j= \"+j + \" i= \" + i + \" n= \" + str.length);\n // console.log(\" skipspace ch <\" + ch + \">\");\n if (whitespace.indexOf(ch) < 0 ) { //not ws\n // console.log(\" skipspace 2 ch <\" + ch + \">\");\n if( str.charAt(j)==='#' ) {\n for (;; j++) {\n // console.log(\" skipspace2 j= \"+j + \" i= \" + i + \" n= \" + str.length);\n if (j === str.length) {\n return -1; // EOF\n }\n if (str.charAt(j) === '\\n') {\n this.lines = this.lines + 1;\n break;\n }\n };\n } else { // Not hash - something interesting\n // console.log(\" skipspace 3 ch <\" + ch + \">\");\n return j\n }\n } else { // Whitespace\n // console.log(\" skipspace 5 ch <\" + ch + \">\");\n if (str.charAt(j) === '\\n') {\n this.lines = this.lines + 1;\n }\n }\n } // next j\n return -1; // EOF\n};\n\n__SinkParser.prototype.variable = function(str, i, res) {\n /*\n ?abc -> variable(:abc)\n */\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n if ((pyjslib_slice(str, j, ( j + 1 ) ) != \"?\")) {\n return -1;\n }\n var j = ( j + 1 ) ;\n var i = j;\n if ((\"0123456789-\".indexOf(str.charAt(j)) >= 0)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, ( ( \"Varible name can't start with '\" + str.charAt(j) ) + \"s'\" ) );\n return -1;\n }\n while ((i < pyjslib_len(str)) && (_notNameChars.indexOf(str.charAt(i)) < 0)) {\n var i = ( i + 1 ) ;\n }\n if ((this._parentContext == null)) {\n throw BadSyntax(this._thisDoc, this.lines, str, j, ( \"Can't use ?xxx syntax for variable in outermost level: \" + pyjslib_slice(str, ( j - 1 ) , i) ) );\n }\n res.push(this._store.variable(pyjslib_slice(str, j, i)));\n return i;\n};\n__SinkParser.prototype.bareWord = function(str, i, res) {\n /*\n abc -> :abc\n */\n\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n var ch = str.charAt(j);\n if ((\"0123456789-\".indexOf(ch) >= 0)) {\n return -1;\n }\n if ((_notNameChars.indexOf(ch) >= 0)) {\n return -1;\n }\n var i = j;\n while ((i < pyjslib_len(str)) && (_notNameChars.indexOf(str.charAt(i)) < 0)) {\n var i = ( i + 1 ) ;\n }\n res.push(pyjslib_slice(str, j, i));\n return i;\n};\n__SinkParser.prototype.qname = function(str, i, res) {\n /*\n\n xyz:def -> ('xyz', 'def')\n If not in keywords and keywordsSet: def -> ('', 'def')\n :def -> ('', 'def')\n */\n\n var i = this.skipSpace(str, i);\n if ((i < 0)) {\n return -1;\n }\n var c = str.charAt(i);\n if ((\"0123456789-+\".indexOf(c) >= 0)) {\n return -1;\n }\n if ((_notNameChars.indexOf(c) < 0)) {\n var ln = c;\n var i = ( i + 1 ) ;\n while ((i < pyjslib_len(str))) {\n var c = str.charAt(i);\n if ((_notNameChars.indexOf(c) < 0)) {\n var ln = ( ln + c ) ;\n var i = ( i + 1 ) ;\n }\n else {\n break;\n }\n }\n }\n else {\n var ln = \"\";\n }\n if ((i < pyjslib_len(str)) && (str.charAt(i) == \":\")) {\n var pfx = ln;\n var i = ( i + 1 ) ;\n var ln = \"\";\n while ((i < pyjslib_len(str))) {\n var c = str.charAt(i);\n if ((_notNameChars.indexOf(c) < 0)) {\n var ln = ( ln + c ) ;\n var i = ( i + 1 ) ;\n }\n else {\n break;\n }\n }\n res.push(new pyjslib_Tuple([pfx, ln]));\n return i;\n }\n else {\n if (ln && this.keywordsSet && (ArrayIndexOf(this.keywords, ln) < 0)) {\n res.push(new pyjslib_Tuple([\"\", ln]));\n return i;\n }\n return -1;\n }\n};\n__SinkParser.prototype.object = function(str, i, res) {\n var j = this.subject(str, i, res);\n if ((j >= 0)) {\n return j;\n }\n else {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n else {\n var i = j;\n }\n var delim = null\n let ch = str.charAt(i)\n if ((ch == \"\\\"\" || ch == \"'\")) {\n if (str.slice(i, ( i + 3 ) == ch + ch)) {\n delim = ch + ch + ch;\n }\n else {\n delim = ch;\n }\n var i = ( i + pyjslib_len(delim) ) ;\n var pairFudge = this.strconst(str, i, delim);\n var j = pairFudge[0];\n var s = pairFudge[1];\n res.push(this._store.literal(s));\n diag_progress(\"New string const \", s, j);\n return j;\n }\n else {\n return -1;\n }\n }\n};\n__SinkParser.prototype.nodeOrLiteral = function(str, i, res) {\n var j = this.node(str, i, res);\n if ((j >= 0)) {\n return j;\n }\n else {\n var j = this.skipSpace(str, i);\n if ((j < 0)) {\n return -1;\n }\n else {\n var i = j;\n }\n var ch = str.charAt(i);\n if ((\"-+0987654321\".indexOf(ch) >= 0)) {\n\n\t datetime_syntax.lastIndex = 0;\n var m = datetime_syntax.exec(str.slice(i));\n if ((m != null)) {\n\t\t// j = ( i + datetime_syntax.lastIndex ) ;\n\t\tvar val = m[0];\n\t\tj = i + val.length;\n\t\tif ((val.indexOf(\"T\") >= 0)) {\n\t\t res.push(this._store.literal(val, undefined, this._store.sym(DATETIME_DATATYPE)));\n\t\t} else {\n\t\t res.push(this._store.literal(val, undefined, this._store.sym(DATE_DATATYPE)));\n\t\t}\n\n\t } else {\n\t\tnumber_syntax.lastIndex = 0;\n\t\tvar m = number_syntax.exec(str.slice(i));\n\t\tif ((m == null)) {\n\t\t throw BadSyntax(this._thisDoc, this.lines, str, i, \"Bad number or date syntax\");\n\t\t}\n\t\tj = ( i + number_syntax.lastIndex ) ;\n\t\tvar val = pyjslib_slice(str, i, j);\n\t\tif ((val.indexOf(\"e\") >= 0)) {\n\t\t res.push(this._store.literal(parseFloat(val), undefined, this._store.sym(FLOAT_DATATYPE)));\n\t\t}\n\t\telse if ((pyjslib_slice(str, i, j).indexOf(\".\") >= 0)) {\n\t\t res.push(this._store.literal(parseFloat(val), undefined, this._store.sym(DECIMAL_DATATYPE)));\n\t\t}\n\t\telse {\n\t\t res.push(this._store.literal(parseInt(val), undefined, this._store.sym(INTEGER_DATATYPE)));\n\t\t}\n\t };\n\t return j; // Where we have got up to\n }\n if ((str.charAt(i) == \"\\\"\")) {\n if ((pyjslib_slice(str, i, ( i + 3 ) ) == \"\\\"\\\"\\\"\")) {\n var delim = \"\\\"\\\"\\\"\";\n }\n else {\n var delim = \"\\\"\";\n }\n var i = ( i + pyjslib_len(delim) ) ;\n var dt = null;\n var pairFudge = this.strconst(str, i, delim);\n var j = pairFudge[0];\n var s = pairFudge[1];\n var lang = null;\n if ((pyjslib_slice(str, j, ( j + 1 ) ) == \"@\")) {\n langcode.lastIndex = 0;\n\n var m = langcode.exec(str.slice( ( j + 1 ) ));\n if ((m == null)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"Bad language code syntax on string literal, after @\");\n }\n var i = ( ( langcode.lastIndex + j ) + 1 ) ;\n\n var lang = pyjslib_slice(str, ( j + 1 ) , i);\n var j = i;\n }\n if ((pyjslib_slice(str, j, ( j + 2 ) ) == \"^^\")) {\n var res2 = new pyjslib_List([]);\n var j = this.uri_ref2(str, ( j + 2 ) , res2);\n var dt = res2[0];\n }\n res.push(this._store.literal(s, lang, dt));\n return j;\n }\n else {\n return -1;\n }\n }\n};\n__SinkParser.prototype.strconst = function(str, i, delim) {\n /*\n parse an N3 string constant delimited by delim.\n return index, val\n */\n\n var j = i;\n var ustr = \"\";\n var startline = this.lines;\n while ((j < pyjslib_len(str))) {\n var i = ( j + pyjslib_len(delim) ) ;\n if ((pyjslib_slice(str, j, i) == delim)) {\n return new pyjslib_Tuple([i, ustr]);\n }\n if ((str.charAt(j) == \"\\\"\")) {\n var ustr = ( ustr + \"\\\"\" ) ;\n var j = ( j + 1 ) ;\n continue;\n }\n interesting.lastIndex = 0;\n var m = interesting.exec(str.slice(j));\n if (!(m)) {\n throw BadSyntax(this._thisDoc, startline, str, j, ( ( ( \"Closing quote missing in string at ^ in \" + pyjslib_slice(str, ( j - 20 ) , j) ) + \"^\" ) + pyjslib_slice(str, j, ( j + 20 ) ) ) );\n }\n var i = ( ( j + interesting.lastIndex ) - 1 ) ;\n var ustr = ( ustr + pyjslib_slice(str, j, i) ) ;\n var ch = str.charAt(i);\n if ((ch == \"\\\"\")) {\n var j = i;\n continue;\n }\n else if ((ch == \"\\r\")) {\n var j = ( i + 1 ) ;\n continue;\n }\n else if ((ch == \"\\n\")) {\n if ((delim == \"\\\"\")) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"newline found in string literal\");\n }\n this.lines = ( this.lines + 1 ) ;\n var ustr = ( ustr + ch ) ;\n var j = ( i + 1 ) ;\n this.previousLine = this.startOfLine;\n this.startOfLine = j;\n }\n else if ((ch == \"\\\\\")) {\n var j = ( i + 1 ) ;\n var ch = pyjslib_slice(str, j, ( j + 1 ) );\n if (!(ch)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"unterminated string literal (2)\");\n }\n var k = string_find(\"abfrtvn\\\\\\\"\", ch);\n if ((k >= 0)) {\n var uch = \"\\a\\b\\f\\r\\t\\v\\n\\\\\\\"\".charAt(k);\n var ustr = ( ustr + uch ) ;\n var j = ( j + 1 ) ;\n }\n else if ((ch == \"u\")) {\n var pairFudge = this.uEscape(str, ( j + 1 ) , startline);\n var j = pairFudge[0];\n var ch = pairFudge[1];\n var ustr = ( ustr + ch ) ;\n }\n else if ((ch == \"U\")) {\n var pairFudge = this.UEscape(str, ( j + 1 ) , startline);\n var j = pairFudge[0];\n var ch = pairFudge[1];\n var ustr = ( ustr + ch ) ;\n }\n else {\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"bad escape\");\n }\n }\n }\n throw BadSyntax(this._thisDoc, this.lines, str, i, \"unterminated string literal\");\n};\n__SinkParser.prototype.uEscape = function(str, i, startline) {\n var j = i;\n var count = 0;\n var value = 0;\n while ((count < 4)) {\n var chFudge = pyjslib_slice(str, j, ( j + 1 ) );\n var ch = chFudge.toLowerCase();\n var j = ( j + 1 ) ;\n if ((ch == \"\")) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"unterminated string literal(3)\");\n }\n var k = string_find(\"0123456789abcdef\", ch);\n if ((k < 0)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"bad string literal hex escape\");\n }\n var value = ( ( value * 16 ) + k ) ;\n var count = ( count + 1 ) ;\n }\n var uch = String.fromCharCode(value);\n return new pyjslib_Tuple([j, uch]);\n};\n__SinkParser.prototype.UEscape = function(str, i, startline) {\n var j = i;\n var count = 0;\n var value = \"\\\\U\";\n while ((count < 8)) {\n var chFudge = pyjslib_slice(str, j, ( j + 1 ) );\n var ch = chFudge.toLowerCase();\n var j = ( j + 1 ) ;\n if ((ch == \"\")) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"unterminated string literal(3)\");\n }\n var k = string_find(\"0123456789abcdef\", ch);\n if ((k < 0)) {\n throw BadSyntax(this._thisDoc, startline, str, i, \"bad string literal hex escape\");\n }\n var value = ( value + ch ) ;\n var count = ( count + 1 ) ;\n }\n var uch = stringFromCharCode( ( ( \"0x\" + pyjslib_slice(value, 2, 10) ) - 0 ) );\n return new pyjslib_Tuple([j, uch]);\n};\nfunction OLD_BadSyntax(uri, lines, str, i, why) {\n return new __OLD_BadSyntax(uri, lines, str, i, why);\n}\nfunction __OLD_BadSyntax(uri, lines, str, i, why) {\n this._str = str.encode(\"utf-8\");\n this._str = str;\n this._i = i;\n this._why = why;\n this.lines = lines;\n this._uri = uri;\n}\n__OLD_BadSyntax.prototype.toString = function() {\n var str = this._str;\n var i = this._i;\n var st = 0;\n if ((i > 60)) {\n var pre = \"...\";\n var st = ( i - 60 ) ;\n }\n else {\n var pre = \"\";\n }\n if (( ( pyjslib_len(str) - i ) > 60)) {\n var post = \"...\";\n }\n else {\n var post = \"\";\n }\n 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, pyjslib_slice(str, st, i), pyjslib_slice(str, i, ( i + 60 ) ), post]);\n};\nfunction BadSyntax(uri, lines, str, i, why) {\n return ( ( ( ( ( ( ( ( \"Line \" + ( lines + 1 ) ) + \" of <\" ) + uri ) + \">: Bad syntax: \" ) + why ) + \"\\nat: \\\"\" ) + pyjslib_slice(str, i, ( i + 30 ) ) ) + \"\\\"\" ) ;\n}\n\n\nfunction stripCR(str) {\n var res = \"\";\n\n var __ch = new pyjslib_Iterator(str);\n try {\n while (true) {\n var ch = __ch.next();\n\n\n if ((ch != \"\\r\")) {\n var res = ( res + ch ) ;\n }\n\n }\n } catch (e) {\n if (e != StopIteration) {\n throw e;\n }\n }\n\n return res;\n}\n\n\nfunction dummyWrite(x) {\n}\n\nreturn SinkParser;\n\n})();\n\nmodule.exports = N3Parser\n","'use strict'\nconst ClassOrder = require('./class-order')\nconst NamedNode = require('./named-node')\nconst Node = require('./node')\nconst XSD = require('./xsd')\n\nclass Literal extends Node {\n constructor (value, language, datatype) {\n super()\n this.termType = Literal.termType\n this.value = value\n if (language) {\n this.lang = language\n datatype = XSD.langString\n }\n // If not specified, a literal has the implied XSD.string default datatype\n if (datatype) {\n this.datatype = NamedNode.fromValue(datatype)\n }\n }\n copy () {\n return new Literal(this.value, this.lang, this.datatype)\n }\n equals (other) {\n if (!other) {\n return false\n }\n return (this.termType === other.termType) &&\n (this.value === other.value) &&\n (this.language === other.language) &&\n ((!this.datatype && !other.datatype) ||\n (this.datatype && this.datatype.equals(other.datatype)))\n }\n get language () {\n return this.lang\n }\n set language (language) {\n this.lang = language || ''\n }\n toNT () {\n if (typeof this.value === 'number') {\n return this.toString()\n } else if (typeof this.value !== 'string') {\n throw new Error('Value of RDF literal is not string or number: ' +\n this.value)\n }\n var str = this.value\n str = str.replace(/\\\\/g, '\\\\\\\\')\n str = str.replace(/\\\"/g, '\\\\\"')\n str = str.replace(/\\n/g, '\\\\n')\n str = '\"' + str + '\"'\n\n if (this.language) {\n str += '@' + this.language\n } else if (!this.datatype.equals(XSD.string)) {\n // Only add datatype if it's not a string\n str += '^^' + this.datatype.toCanonical()\n }\n return str\n }\n toString () {\n return '' + this.value\n }\n /**\n * @method fromBoolean\n * @static\n * @param value {Boolean}\n * @return {Literal}\n */\n static fromBoolean (value) {\n let strValue = value ? '1' : '0'\n return new Literal(strValue, null, XSD.boolean)\n }\n /**\n * @method fromDate\n * @static\n * @param value {Date}\n * @return {Literal}\n */\n static fromDate (value) {\n if (!(value instanceof Date)) {\n throw new TypeError('Invalid argument to Literal.fromDate()')\n }\n let d2 = function (x) {\n return ('' + (100 + x)).slice(1, 3)\n }\n let date = '' + value.getUTCFullYear() + '-' + d2(value.getUTCMonth() + 1) +\n '-' + d2(value.getUTCDate()) + 'T' + d2(value.getUTCHours()) + ':' +\n d2(value.getUTCMinutes()) + ':' + d2(value.getUTCSeconds()) + 'Z'\n return new Literal(date, null, XSD.dateTime)\n }\n /**\n * @method fromNumber\n * @static\n * @param value {Number}\n * @return {Literal}\n */\n static fromNumber (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Invalid argument to Literal.fromNumber()')\n }\n let datatype\n const strValue = value.toString()\n if (strValue.indexOf('e') < 0 && Math.abs(value) <= Number.MAX_SAFE_INTEGER) {\n datatype = Number.isInteger(value) ? XSD.integer : XSD.decimal\n } else {\n datatype = XSD.double\n }\n return new Literal(strValue, null, datatype)\n }\n /**\n * @method fromValue\n * @param value\n * @return {Literal}\n */\n static fromValue (value) {\n if (typeof value === 'undefined' || value === null) {\n return value\n }\n if (typeof value === 'object' && value.termType) { // this is a Node instance\n return value\n }\n switch (typeof value) {\n case 'object':\n if (value instanceof Date) {\n return Literal.fromDate(value)\n }\n case 'boolean':\n return Literal.fromBoolean(value)\n case 'number':\n return Literal.fromNumber(value)\n case 'string':\n return new Literal(value)\n }\n throw new Error(\"Can't make literal from \" + value + ' of type ' +\n typeof value)\n\n }\n}\nLiteral.termType = 'Literal'\nLiteral.prototype.classOrder = ClassOrder['Literal']\nLiteral.prototype.datatype = XSD.string\nLiteral.prototype.lang = ''\nLiteral.prototype.isVar = 0\n\nmodule.exports = Literal\n"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 59);\n","'use strict'\nconst ClassOrder = require('./class-order')\nconst Node = require('./node')\n\n/**\n * @class NamedNode\n * @extends Node\n */\nclass NamedNode extends Node {\n /**\n * @constructor\n * @param iri {String}\n */\n constructor (iri) {\n super()\n this.termType = NamedNode.termType\n\n if (iri && iri.termType === NamedNode.termType) { // param is a named node\n iri = iri.value\n }\n\n if (!iri) {\n throw new Error('Missing IRI for NamedNode')\n }\n\n if (!iri.includes(':')) {\n throw new Error('NamedNode IRI \"' + iri + '\" must be absolute.')\n }\n\n if (iri.includes(' ')) {\n var message = 'Error: NamedNode IRI \"' + iri + '\" must not contain unencoded spaces.'\n throw new Error(message)\n }\n\n this.value = iri\n }\n /**\n * Returns an $rdf node for the containing directory, ending in slash.\n */\n dir () {\n var str = this.uri.split('#')[0]\n var p = str.slice(0, -1).lastIndexOf('/')\n var q = str.indexOf('//')\n if ((q >= 0 && p < q + 2) || p < 0) return null\n return new NamedNode(str.slice(0, p + 1))\n }\n /**\n * Returns an NN for the whole web site, ending in slash.\n * Contrast with the \"origin\" which does NOT have a trailing slash\n */\n site () {\n var str = this.uri.split('#')[0]\n var p = str.indexOf('//')\n if (p < 0) throw new Error('This URI does not have a web site part (origin)')\n var q = str.indexOf('/', p+2)\n if (q < 0) throw new Error('This URI does not have a web site part. (origin)')\n return new NamedNode(str.slice(0, q + 1))\n }\n doc () {\n if (this.uri.indexOf('#') < 0) {\n return this\n } else {\n return new NamedNode(this.uri.split('#')[0])\n }\n }\n toString () {\n return '<' + this.uri + '>'\n }\n\n /**\n * Legacy getter and setter alias, node.uri\n */\n get uri () {\n return this.value\n }\n set uri (uri) {\n this.value = uri\n }\n static fromValue (value) {\n if (typeof value === 'undefined' || value === null) {\n return value\n }\n const isNode = value && value.termType\n if (isNode) {\n return value\n }\n return new NamedNode(value)\n }\n}\nNamedNode.termType = 'NamedNode'\nNamedNode.prototype.classOrder = ClassOrder['NamedNode']\nNamedNode.prototype.isVar = 0\n\nmodule.exports = NamedNode\n","'use strict'\n/**\n * The superclass of all RDF Statement objects, that is\n * NamedNode, Literal, BlankNode, etc.\n * @class Node\n */\nclass Node {\n substitute (bindings) {\n console.log('@@@ node substitute' + this)\n return this\n }\n compareTerm (other) {\n if (this.classOrder < other.classOrder) {\n return -1\n }\n if (this.classOrder > other.classOrder) {\n return +1\n }\n if (this.value < other.value) {\n return -1\n }\n if (this.value > other.value) {\n return +1\n }\n return 0\n }\n equals (other) {\n if (!other) {\n return false\n }\n return (this.termType === other.termType) &&\n (this.value === other.value)\n }\n hashString () {\n return this.toCanonical()\n }\n sameTerm (other) {\n return this.equals(other)\n }\n toCanonical () {\n return this.toNT()\n }\n toNT () {\n return this.toString()\n }\n toString () {\n throw new Error('Node.toString() is abstract - see the subclasses instead')\n }\n}\nmodule.exports = Node\n\n/**\n * Creates an RDF Node from a native javascript value.\n * RDF Nodes are returned unchanged, undefined returned as itself.\n * @method fromValue\n * @static\n * @param value {Node|Date|String|Number|Boolean|Undefined}\n * @return {Node|Collection}\n */\nNode.fromValue = function fromValue (value) {\n const Collection = require('./collection')\n const Literal = require('./literal')\n const NamedNode = require('./named-node')\n if (typeof value === 'undefined' || value === null) {\n return value\n }\n const isNode = value && value.termType\n if (isNode) { // a Node subclass or a Collection\n return value\n }\n if (Array.isArray(value)) {\n return new Collection(value)\n }\n return Literal.fromValue(value)\n}\n\nNode.toJS = function fromJS (term) {\n if (term.elements) {\n return term.elements.map(Node.toJS) // Array node (not standard RDFJS)\n }\n if (!term.datatype) return term // Objects remain objects\n if (term.datatype.equals(ns.xsd('boolean'))) {\n return term.value === '1'\n }\n if (term.datatype.equals(ns.xsd('dateTime')) ||\n term.datatype.equals(ns.xsd('date'))) {\n return new Date(term.value)\n }\n if (\n term.datatype.equals(ns.xsd('integer')) ||\n term.datatype.equals(ns.xsd('float')) ||\n term.datatype.equals(ns.xsd('decimal'))\n ) {\n return Number(term.value)\n }\n return term.value\n}\n","/*\n * Implements URI-specific functions\n *\n * See RFC 2386\n *\n * See also:\n * http://www.w3.org/2005/10/ajaw/uri.js\n * http://www.w3.org/2000/10/swap/uripath.py\n *\n */\nvar alert = alert || console.log\n\nmodule.exports.docpart = docpart\nmodule.exports.document = document\nmodule.exports.hostpart = hostpart\nmodule.exports.join = join\nmodule.exports.protocol = protocol\nmodule.exports.refTo = refTo\n\nconst NamedNode = require('./named-node')\n\nfunction docpart (uri) {\n var i\n i = uri.indexOf('#')\n if (i < 0) {\n return uri\n } else {\n return uri.slice(0, i)\n }\n}\n\nfunction document (x) {\n return new NamedNode(docpart(x.uri))\n}\n\nfunction hostpart (u) {\n var m = /[^\\/]*\\/\\/([^\\/]*)\\//.exec(u)\n if (m) {\n return m[1]\n } else {\n return ''\n }\n}\n\nfunction join (given, base) {\n var baseColon, baseScheme, baseSingle\n var colon, lastSlash, path\n var baseHash = base.indexOf('#')\n if (baseHash > 0) {\n base = base.slice(0, baseHash)\n }\n if (given.length === 0) {\n return base\n }\n if (given.indexOf('#') === 0) {\n return base + given\n }\n colon = given.indexOf(':')\n if (colon >= 0) {\n return given\n }\n baseColon = base.indexOf(':')\n if (base.length === 0) {\n return given\n }\n if (baseColon < 0) {\n alert('Invalid base: ' + base + ' in join with given: ' + given)\n return given\n }\n baseScheme = base.slice(0, +baseColon + 1 || 9e9)\n if (given.indexOf('//') === 0) {\n return baseScheme + given\n }\n if (base.indexOf('//', baseColon) === baseColon + 1) {\n baseSingle = base.indexOf('/', baseColon + 3)\n if (baseSingle < 0) {\n if (base.length - baseColon - 3 > 0) {\n return base + '/' + given\n } else {\n return baseScheme + given\n }\n }\n } else {\n baseSingle = base.indexOf('/', baseColon + 1)\n if (baseSingle < 0) {\n if (base.length - baseColon - 1 > 0) {\n return base + '/' + given\n } else {\n return baseScheme + given\n }\n }\n }\n if (given.indexOf('/') === 0) {\n return base.slice(0, baseSingle) + given\n }\n path = base.slice(baseSingle)\n lastSlash = path.lastIndexOf('/')\n if (lastSlash < 0) {\n return baseScheme + given\n }\n if (lastSlash >= 0 && lastSlash < path.length - 1) {\n path = path.slice(0, +lastSlash + 1 || 9e9)\n }\n path += given\n while (path.match(/[^\\/]*\\/\\.\\.\\//)) {\n path = path.replace(/[^\\/]*\\/\\.\\.\\//, '')\n }\n path = path.replace(/\\.\\//g, '')\n path = path.replace(/\\/\\.$/, '/')\n return base.slice(0, baseSingle) + path\n}\n\nfunction protocol (uri) {\n var i\n i = uri.indexOf(':')\n if (i < 0) {\n return null\n } else {\n return uri.slice(0, i)\n }\n}\n\nfunction refTo (base, uri) {\n var c, i, k, l, len, len1, n, o, p, q, ref, ref1, s\n var commonHost = new RegExp('^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$')\n if (!base) {\n return uri\n }\n if (base === uri) {\n return ''\n }\n for (i = o = 0, len = uri.length; o < len; i = ++o) {\n c = uri[i]\n if (c !== base[i]) {\n break\n }\n }\n if (base.slice(0, i).match(commonHost)) {\n k = uri.indexOf('//')\n if (k < 0) {\n k = -2\n }\n l = uri.indexOf('/', k + 2)\n if (uri[l + 1] !== '/' && base[l + 1] !== '/' && uri.slice(0, l) === base.slice(0, l)) {\n return uri.slice(l)\n }\n }\n if (uri[i] === '#' && base.length === i) {\n return uri.slice(i)\n }\n while (i > 0 && uri[i - 1] !== '/') {\n i--\n }\n if (i < 3) {\n return uri\n }\n if (base.indexOf('//', i - 2) > 0 || uri.indexOf('//', i - 2) > 0) {\n return uri\n }\n if (base.indexOf(':', i) > 0) {\n return uri\n }\n n = 0\n ref = base.slice(i)\n for (p = 0, len1 = ref.length; p < len1; p++) {\n c = ref[p]\n if (c === '/') {\n n++\n }\n }\n if (n === 0 && i < uri.length && uri[i] === '#') {\n return './' + uri.slice(i)\n }\n if (n === 0 && i === uri.length) {\n return './'\n }\n s = ''\n if (n > 0) {\n for (q = 1, ref1 = n; ref1 >= 1 ? q <= ref1 : q >= ref1; ref1 >= 1 ? ++q : --q) {\n s += '../'\n }\n }\n return s + uri.slice(i)\n}\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || Function(\"return this\")() || (1, eval)(\"this\");\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","/**\n * Utility functions for $rdf\n * @module util\n */\nvar docpart = require('./uri').docpart\nvar log = require('./log')\nvar NamedNode = require('./named-node')\n\nmodule.exports.AJAR_handleNewTerm = ajarHandleNewTerm\nmodule.exports.ArrayIndexOf = arrayIndexOf\nmodule.exports.callbackify = callbackify\nmodule.exports.dtstamp = dtstamp\nmodule.exports.DOMParserFactory = domParser\nmodule.exports.domToString = domToString\nmodule.exports.dumpNode = dumpNode\nmodule.exports.heavyCompare = heavyCompare\nmodule.exports.heavyCompareSPO = heavyCompareSPO\nmodule.exports.output = output\nmodule.exports.parseXML = parseXML\nmodule.exports.RDFArrayRemove = rdfArrayRemove\nmodule.exports.stackString = stackString\nmodule.exports.string_startswith = stringStartsWith\nmodule.exports.string = {}\nmodule.exports.string.template = stringTemplate\nmodule.exports.uri = require('./uri') // TODO: Remove this mixed usage\nmodule.exports.log = log\n\nmodule.exports.mediaTypeClass = function(mediaType){\n mediaType = mediaType.split(';')[0].trim() // remove media type parameters\n return new NamedNode('http://www.w3.org/ns/iana/media-types/' + mediaType + '#Resource')\n}\n\nmodule.exports.linkRelationProperty = function(relation){\n return new NamedNode('http://www.w3.org/ns/iana/link-relations/relation#' + relation.trim())\n}\n\n/**\n * Loads ontologies of the data we load (this is the callback from the kb to\n * the fetcher). Exports as `AJAR_handleNewTerm`\n */\nfunction ajarHandleNewTerm (kb, p, requestedBy) {\n var sf = null\n if (typeof kb.fetcher !== 'undefined') {\n sf = kb.fetcher\n } else {\n return\n }\n if (p.termType !== 'NamedNode') return\n var docuri = docpart(p.uri)\n var fixuri\n if (p.uri.indexOf('#') < 0) { // No hash\n // @@ major hack for dbpedia Categories, which spread indefinitely\n if (stringStartsWith(p.uri, 'http://dbpedia.org/resource/Category:')) return\n\n /*\n if (string_startswith(p.uri, 'http://xmlns.com/foaf/0.1/')) {\n fixuri = \"http://dig.csail.mit.edu/2005/ajar/ajaw/test/foaf\"\n // should give HTTP 303 to ontology -- now is :-)\n } else\n */\n if (stringStartsWith(p.uri,\n 'http://purl.org/dc/elements/1.1/') ||\n stringStartsWith(p.uri, 'http://purl.org/dc/terms/')) {\n fixuri = 'http://dublincore.org/2005/06/13/dcq'\n // dc fetched multiple times\n } else if (stringStartsWith(p.uri, 'http://xmlns.com/wot/0.1/')) {\n fixuri = 'http://xmlns.com/wot/0.1/index.rdf'\n } else if (stringStartsWith(p.uri, 'http://web.resource.org/cc/')) {\n // log.warn(\"creative commons links to html instead of rdf. doesn't seem to content-negotiate.\")\n fixuri = 'http://web.resource.org/cc/schema.rdf'\n }\n }\n if (fixuri) {\n docuri = fixuri\n }\n if (sf && sf.getState(docuri) !== 'unrequested') return\n\n if (fixuri) { // only give warning once: else happens too often\n log.warn('Assuming server still broken, faking redirect of <' + p.uri +\n '> to <' + docuri + '>')\n }\n\n return sf.fetch(docuri, { referringTerm: requestedBy })\n}\n\n/**\n * Exports as `ArrayIndexOf`.\n */\nfunction arrayIndexOf (arr, item, i) {\n i || (i = 0)\n var length = arr.length\n if (i < 0) i = length + i\n for (; i < length; i++) {\n if (arr[i] === item) {\n return i\n }\n }\n return -1\n}\n\n/**\n * Adds callback functionality to an object.\n * Callback functions are indexed by a 'hook' string.\n * They return true if they want to be called again.\n * @method callbackify\n * @param obj {Object}\n * @param callbacks {Array}\n */\nfunction callbackify (obj, callbacks) {\n obj.callbacks = {}\n for (var x = callbacks.length - 1; x >= 0; x--) {\n obj.callbacks[callbacks[x]] = []\n }\n\n obj.addHook = function (hook) {\n if (!obj.callbacks[hook]) {\n obj.callbacks[hook] = []\n }\n }\n\n obj.addCallback = function (hook, func) {\n obj.callbacks[hook].push(func)\n }\n\n obj.removeCallback = function (hook, funcName) {\n for (var i = 0;i < obj.callbacks[hook].length;i++) {\n if (obj.callbacks[hook][i].name === funcName) {\n obj.callbacks[hook].splice(i, 1)\n return true\n }\n }\n return false\n }\n\n obj.insertCallback = function (hook, func) {\n obj.callbacks[hook].unshift(func)\n }\n\n obj.fireCallbacks = function fireCallbacks (hook, args) {\n var newCallbacks = []\n var replaceCallbacks = []\n var len = obj.callbacks[hook].length\n var x\n let callback\n\n // log.info('!@$ Firing '+hook+' call back with length'+len)\n for (x = len - 1; x >= 0; x--) {\n // log.info('@@ Firing '+hook+' callback '+ obj.callbacks[hook][x])\n callback = obj.callbacks[hook][x]\n if (callback && callback.apply(obj, args)) {\n newCallbacks.push(callback)\n }\n }\n\n for (x = newCallbacks.length - 1; x >= 0; x--) {\n replaceCallbacks.push(newCallbacks[x])\n }\n\n for (x = len; x < obj.callbacks[hook].length; x++) {\n replaceCallbacks.push(obj.callbacks[hook][x])\n }\n\n obj.callbacks[hook] = replaceCallbacks\n }\n}\n\n/**\n * Returns a DOM parser based on current runtime environment.\n * Exports as `DOMParserFactory`\n */\nfunction domParser () {\n if (window.DOMParser) {\n return new DOMParser()\n } else if (window.ActiveXObject) {\n return new ActiveXObject('Microsoft.XMLDOM')\n } else {\n return false\n }\n}\n\n// From https://github.com/linkeddata/dokieli\nfunction domToString (node, options) {\n options = options || {}\n var selfClosing = []\n if ('selfClosing' in options) {\n options.selfClosing.split(' ').forEach(function (n) {\n selfClosing[n] = true\n })\n }\n var skipAttributes = []\n if ('skipAttributes' in options) {\n options.skipAttributes.split(' ').forEach(function (n) {\n skipAttributes[n] = true\n })\n }\n return dumpNode(node, options, selfClosing, skipAttributes)\n}\n\nfunction dumpNode (node, options, selfClosing, skipAttributes) {\n var i\n var out = ''\n var noEsc = [ false ]\n if (typeof node.nodeType === 'undefined') return out\n if (node.nodeType === 1) {\n if (node.hasAttribute('class') && 'classWithChildText' in options && node.matches(options.classWithChildText.class)) {\n out += node.querySelector(options.classWithChildText.element).textContent\n } else if (!('skipNodeWithClass' in options && node.matches('.' + options.skipNodeWithClass))) {\n var ename = node.nodeName.toLowerCase()\n out += '<' + ename\n\n var attrList = []\n for (i = node.attributes.length - 1; i >= 0; i--) {\n var atn = node.attributes[i]\n if (skipAttributes.length > 0 && skipAttributes[atn.name]) continue\n if (/^\\d+$/.test(atn.name)) continue\n if (atn.name === 'class' && 'replaceClassItemWith' in options && (atn.value.split(' ').indexOf(options.replaceClassItemWith.source) > -1)) {\n var re = new RegExp(options.replaceClassItemWith.source, 'g')\n atn.value = atn.value.replace(re, options.replaceClassItemWith.target).trim()\n }\n if (!(atn.name === 'class' && 'skipClassWithValue' in options && options.skipClassWithValue === atn.value)) {\n attrList.push(atn.name + '=\\'' + atn.value.replace(/&/g, '&').replace(//g, '>').replace(/'/g, '"') + '\\'')\n }\n }\n if (attrList.length > 0) {\n if ('sortAttributes' in options && options.sortAttributes) {\n attrList.sort(function (a, b) {\n return a.toLowerCase().localeCompare(b.toLowerCase())\n })\n }\n out += ' ' + attrList.join(' ')\n }\n if (selfClosing[ename]) {\n out += ' />'\n } else {\n out += '>'\n out += (ename === 'html') ? '\\n ' : ''\n noEsc.push(ename === 'style' || ename === 'script')\n for (i = 0; i < node.childNodes.length; i++) out += dumpNode(node.childNodes[i])\n noEsc.pop()\n out += (ename === 'body') ? '' + '\\n' : ''\n }\n }\n } else if (node.nodeType === 8) {\n // FIXME: If comments are not tabbed in source, a new line is not prepended\n out += ''\n } else if (node.nodeType === 3 || node.nodeType === 4) {\n // XXX: Remove new lines which were added after DOM ready\n var nl = node.nodeValue.replace(/\\n+$/, '')\n out += noEsc[noEsc.length - 1] ? nl : nl.replace(/&/g, '&').replace(//g, '>')\n } else {\n console.log('Warning; Cannot handle serialising nodes of type: ' + node.nodeType)\n console.log(node)\n }\n return out\n}\n\nfunction dtstamp () {\n var now = new Date()\n var year = now.getYear() + 1900\n var month = now.getMonth() + 1\n var day = now.getDate()\n var hour = now.getUTCHours()\n var minute = now.getUTCMinutes()\n var second = now.getSeconds()\n if (month < 10) month = '0' + month\n if (day < 10) day = '0' + day\n if (hour < 10) hour = '0' + hour\n if (minute < 10) minute = '0' + minute\n if (second < 10) second = '0' + second\n return year + '-' + month + '-' + day + 'T' +\n hour + ':' + minute + ':' + second + 'Z'\n}\n\n/**\n * Compares statements (heavy comparison for repeatable canonical ordering)\n */\nfunction heavyCompare (x, y, g, uriMap) {\n var nonBlank = function (x) {\n return (x.termType === 'BlankNode') ? null : x\n }\n var signature = function (x) {\n var lis = g.statementsMatching(x).map(function (st) {\n return ('' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) +\n ' ' + nonBlank(st.object))\n }).concat(g.statementsMatching(undefined, undefined, x).map(function (st) {\n return ('' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) +\n ' ' + nonBlank(st.object))\n }))\n lis.sort()\n return lis.join('\\n')\n }\n if ((x.termType === 'BlankNode') && (y.termType === 'BlankNode')) {\n if (x.compareTerm(y) === 0) return 0 // Same\n if (signature(x) > signature(y)) return +1\n if (signature(x) < signature(y)) return -1\n return x.compareTerm(y) // Too bad -- this order not canonical.\n // throw \"different bnodes indistinquishable for sorting\"\n } else {\n if (uriMap && x.uri && y.uri){\n return (uriMap[x.uri] || x.uri).localeCompare(uriMap[y.uri] || y.uri)\n }\n return x.compareTerm(y)\n }\n}\n\nfunction heavyCompareSPO (x, y, g, uriMap) {\n return heavyCompare(x.subject, y.subject, g, uriMap) ||\n heavyCompare(x.predicate, y.predicate, g, uriMap) ||\n heavyCompare(x.object, y.object, g, uriMap)\n}\n\n/**\n * Defines a simple debugging function\n * @method output\n * @param o {String}\n */\nfunction output (o) {\n var k = document.createElement('div')\n k.textContent = o\n document.body.appendChild(k)\n}\n\n/**\n * Returns a DOM from parsex XML.\n */\nfunction parseXML (str, options) {\n var dparser\n options = options || {}\n if (typeof module !== 'undefined' && module && module.exports) { // Node.js\n // var libxmljs = require('libxmljs'); // Was jsdom before 2012-01 then libxmljs but that nonstandard\n // return libxmljs.parseXmlString(str)\n\n // var jsdom = require('jsdom'); 2012-01 though 2015-08 no worky with new Node\n // var dom = jsdom.jsdom(str, undefined, {} );// html, level, options\n\n var DOMParser = require('xmldom').DOMParser // 2015-08 on https://github.com/jindw/xmldom\n var dom = new DOMParser().parseFromString(str, options.contentType || 'application/xhtml+xml')\n return dom\n } else {\n if (typeof window !== 'undefined' && window.DOMParser) {\n dparser = new window.DOMParser() // seems to actually work\n } else {\n dparser = new DOMParser() // Doc says this works\n }\n }\n return dparser.parseFromString(str, 'application/xml')\n}\n\n/**\n * Removes all statements equal to x from a\n * Exports as `RDFArrayRemove`\n */\nfunction rdfArrayRemove (a, x) {\n for (var i = 0; i < a.length; i++) {\n // TODO: This used to be the following, which didnt always work..why\n // if(a[i] === x)\n if (a[i].subject.sameTerm(x.subject) &&\n a[i].predicate.sameTerm(x.predicate) &&\n a[i].object.sameTerm(x.object) &&\n a[i].why.sameTerm(x.why)) {\n a.splice(i, 1)\n return\n }\n }\n throw new Error('RDFArrayRemove: Array did not contain ' + x + ' ' + x.why)\n}\n\nfunction stringStartsWith (str, pref) { // missing library routines\n return (str.slice(0, pref.length) === pref)\n}\n\n/**\n * C++, python style %s -> subs\n */\nfunction stringTemplate (base, subs) {\n var baseA = base.split('%s')\n var result = ''\n for (var i = 0;i < subs.length;i++) {\n subs[i] += ''\n result += baseA[i] + subs[i]\n }\n return result + baseA.slice(subs.length).join()\n}\n\n\n// Stack dump on errors - to pass errors back\n\nfunction stackString (e) {\n var str = '' + e + '\\n'\n if (!e.stack) {\n return str + 'No stack available.\\n'\n }\n var lines = e.stack.toString().split('\\n')\n var toprint = []\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i]\n if (line.indexOf('ecmaunit.js') > -1) {\n // remove useless bit of traceback\n break\n }\n if (line.charAt(0) == '(') {\n line = 'function' + line\n }\n var chunks = line.split('@')\n toprint.push(chunks)\n }\n // toprint.reverse(); No - I prefer the latest at the top by the error message -tbl\n\n for (var i = 0; i < toprint.length; i++) {\n str += ' ' + toprint[i][1] + '\\n ' + toprint[i][0]\n }\n return str\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","'use strict'\nconst ClassOrder = require('./class-order')\nconst Node = require('./node')\n\nclass BlankNode extends Node {\n constructor (id) {\n super()\n this.termType = BlankNode.termType\n\n if (id) {\n if (typeof id !== 'string') {\n console.log('Bad blank id:', id)\n throw new Error('Bad id argument to new blank node: ' + id)\n }\n if (id.includes('#')) {\n // Is a URI with hash fragment\n let fragments = id.split('#')\n id = fragments[fragments.length - 1]\n }\n this.id = id\n // this.id = '' + BlankNode.nextId++\n } else {\n this.id = 'n' + BlankNode.nextId++\n }\n\n this.value = this.id\n }\n\n compareTerm (other) {\n if (this.classOrder < other.classOrder) {\n return -1\n }\n if (this.classOrder > other.classOrder) {\n return +1\n }\n if (this.id < other.id) {\n return -1\n }\n if (this.id > other.id) {\n return +1\n }\n return 0\n }\n\n copy (formula) { // depends on the formula\n var bnodeNew = new BlankNode()\n formula.copyTo(this, bnodeNew)\n return bnodeNew\n }\n\n toCanonical () {\n return '_:' + this.value\n }\n\n toString () {\n return BlankNode.NTAnonymousNodePrefix + this.id\n }\n}\n\nBlankNode.nextId = 0\nBlankNode.termType = 'BlankNode'\nBlankNode.NTAnonymousNodePrefix = '_:'\nBlankNode.prototype.classOrder = ClassOrder['BlankNode']\nBlankNode.prototype.isBlank = 1\nBlankNode.prototype.isVar = 1\n\nmodule.exports = BlankNode\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","/**\n * A Dummy log\n * @module log\n */\nmodule.exports = {\n debug: function debug (x) {\n return\n },\n warn: function warn (x) {\n return\n },\n info: function info (x) {\n return\n },\n error: function error (x) {\n return\n },\n success: function success (x) {\n return\n },\n msg: function msg (x) {\n return\n }\n}\n","var ClassOrder = {\n 'Literal': 1,\n 'Collection': 3,\n 'Graph': 4,\n 'NamedNode': 5,\n 'BlankNode': 6,\n 'Variable': 7\n}\n\nmodule.exports = ClassOrder\n","// Ignore module for browserify (see package.json)","var scope = (typeof global !== \"undefined\" && global) ||\n (typeof self !== \"undefined\" && self) ||\n window;\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(scope, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\nrequire(\"setimmediate\");\n// On some exotic environments, it's not clear which object `setimmediate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","/** Identity management and indexing for RDF\n *\n * This file provides IndexedFormula a formula (set of triples) which\n * indexed by predicate, subject and object.\n *\n * It \"smushes\" (merges into a single node) things which are identical\n * according to owl:sameAs or an owl:InverseFunctionalProperty\n * or an owl:FunctionalProperty\n *\n *\n * 2005-10 Written Tim Berners-Lee\n * 2007 Changed so as not to munge statements from documents when smushing\n *\n *\n * jsl:option explicit\n/** @file: indexed-formula.js\n*/\n\nconst ArrayIndexOf = require('./util').ArrayIndexOf\nconst Formula = require('./formula')\n// const log = require('./log')\nconst RDFArrayRemove = require('./util').RDFArrayRemove\nconst Statement = require('./statement')\nconst Node = require('./node')\nconst Variable = require('./variable')\n\nconst owl_ns = 'http://www.w3.org/2002/07/owl#'\n\nconst defaultGraphURI = 'chrome:theSession'\n// var link_ns = 'http://www.w3.org/2007/ont/link#'\n\n// Handle Functional Property\nfunction handle_FP (formula, subj, pred, obj) {\n var o1 = formula.any(subj, pred, undefined)\n if (!o1) {\n return false // First time with this value\n }\n // log.warn(\"Equating \"+o1.uri+\" and \"+obj.uri + \" because FP \"+pred.uri); //@@\n formula.equate(o1, obj)\n return true\n} // handle_FP\n\n// Handle Inverse Functional Property\nfunction handle_IFP (formula, subj, pred, obj) {\n var s1 = formula.any(undefined, pred, obj)\n if (!s1) {\n return false // First time with this value\n }\n // log.warn(\"Equating \"+s1.uri+\" and \"+subj.uri + \" because IFP \"+pred.uri); //@@\n formula.equate(s1, subj)\n return true\n} // handle_IFP\n\nfunction handleRDFType (formula, subj, pred, obj, why) {\n if (formula.typeCallback) {\n formula.typeCallback(formula, obj, why)\n }\n\n var x = formula.classActions[obj.hashString()]\n var done = false\n if (x) {\n for (var i = 0; i < x.length; i++) {\n done = done || x[i](formula, subj, pred, obj, why)\n }\n }\n return done // statement given is not needed if true\n}\n/**\n * IndexedFormula\n */\nclass IndexedFormula extends Formula { // IN future - allow pass array of statements to constructor\n /**\n * @constructor\n * @param {Array} features - What sort of autmatic processing to do? Array of string\n * @param {Boolean} features.sameAs - Smush together A and B nodes whenever { A sameAs B }\n */\n constructor (features) {\n super()\n // this.statements = [] // As in Formula NO don't overwrite inherited\n // this.optional = []\n\n this.propertyActions = [] // Array of functions to call when getting statement with {s X o}\n // maps to [f(F,s,p,o),...]\n this.classActions = [] // Array of functions to call when adding { s type X }\n this.redirections = [] // redirect to lexically smaller equivalent symbol\n this.aliases = [] // reverse mapping to redirection: aliases for this\n this.HTTPRedirects = [] // redirections we got from HTTP\n this.subjectIndex = [] // Array of statements with this X as subject\n this.predicateIndex = [] // Array of statements with this X as subject\n this.objectIndex = [] // Array of statements with this X as object\n this.whyIndex = [] // Array of statements with X as provenance\n this.index = [\n this.subjectIndex,\n this.predicateIndex,\n this.objectIndex,\n this.whyIndex\n ]\n this.namespaces = {} // Dictionary of namespace prefixes\n this.features = features || [\n 'sameAs',\n 'InverseFunctionalProperty',\n 'FunctionalProperty'\n ]\n this.initPropertyActions(this.features)\n }\n\n static get defaultGraphURI() {\n return defaultGraphURI;\n }\n\n substitute (bindings) {\n var statementsCopy = this.statements.map(function (ea) {\n return ea.substitute(bindings)\n })\n // console.log('IndexedFormula subs statemnts:' + statementsCopy)\n var y = new IndexedFormula()\n y.add(statementsCopy)\n // console.log('indexed-form subs formula:' + y)\n return y\n }\n\n applyPatch (patch, target, patchCallback) { // patchCallback(err)\n const Query = require('./query').Query\n var targetKB = this\n var ds\n var binding = null\n\n // /////////// Debug strings\n /*\n var bindingDebug = function (b) {\n var str = ''\n var v\n for (v in b) {\n if (b.hasOwnProperty(v)) {\n str += ' ' + v + ' -> ' + b[v]\n }\n }\n return str\n }\n*/\n var doPatch = function (onDonePatch) {\n if (patch['delete']) {\n ds = patch['delete']\n // console.log(bindingDebug(binding))\n // console.log('ds before substitute: ' + ds)\n if (binding) ds = ds.substitute(binding)\n // console.log('applyPatch: delete: ' + ds)\n ds = ds.statements\n var bad = []\n var ds2 = ds.map(function (st) { // Find the actual statemnts in the store\n var sts = targetKB.statementsMatching(st.subject, st.predicate, st.object, target)\n if (sts.length === 0) {\n // log.info(\"NOT FOUND deletable \" + st)\n bad.push(st)\n return null\n } else {\n // log.info(\"Found deletable \" + st)\n return sts[0]\n }\n })\n if (bad.length) {\n // console.log('Could not find to delete ' + bad.length + 'statements')\n // console.log('despite ' + targetKB.statementsMatching(bad[0].subject, bad[0].predicate)[0])\n return patchCallback('Could not find to delete: ' + bad.join('\\n or '))\n }\n ds2.map(function (st) {\n targetKB.remove(st)\n })\n }\n if (patch['insert']) {\n // log.info(\"doPatch insert \"+patch['insert'])\n ds = patch['insert']\n if (binding) ds = ds.substitute(binding)\n ds = ds.statements\n ds.map(function (st) {\n st.why = target\n targetKB.add(st.subject, st.predicate, st.object, st.why)\n })\n }\n onDonePatch()\n }\n if (patch.where) {\n // log.info(\"Processing WHERE: \" + patch.where + '\\n')\n var query = new Query('patch')\n query.pat = patch.where\n query.pat.statements.map(function (st) {\n st.why = target\n })\n\n var bindingsFound = []\n\n targetKB.query(query, function onBinding (binding) {\n bindingsFound.push(binding)\n // console.log(' got a binding: ' + bindingDebug(binding))\n },\n targetKB.fetcher,\n function onDone () {\n if (bindingsFound.length === 0) {\n return patchCallback('No match found to be patched:' + patch.where)\n }\n if (bindingsFound.length > 1) {\n return patchCallback('Patch ambiguous. No patch done.')\n }\n binding = bindingsFound[0]\n doPatch(patchCallback)\n })\n } else {\n doPatch(patchCallback)\n }\n }\n\n declareExistential (x) {\n if (!this._existentialVariables) this._existentialVariables = []\n this._existentialVariables.push(x)\n return x\n }\n\n initPropertyActions (features) {\n // If the predicate is #type, use handleRDFType to create a typeCallback on the object\n this.propertyActions[''] =\n [ handleRDFType ]\n\n // Assumption: these terms are not redirected @@fixme\n if (ArrayIndexOf(features, 'sameAs') >= 0) {\n this.propertyActions[''] = [\n function (formula, subj, pred, obj, why) {\n // log.warn(\"Equating \"+subj.uri+\" sameAs \"+obj.uri); //@@\n formula.equate(subj, obj)\n return true // true if statement given is NOT needed in the store\n }\n ] // sameAs -> equate & don't add to index\n }\n if (ArrayIndexOf(features, 'InverseFunctionalProperty') >= 0) {\n this.classActions['<' + owl_ns + 'InverseFunctionalProperty>'] = [\n function (formula, subj, pred, obj, addFn) {\n // yes subj not pred!\n return formula.newPropertyAction(subj, handle_IFP)\n }\n ] // IFP -> handle_IFP, do add to index\n }\n if (ArrayIndexOf(features, 'FunctionalProperty') >= 0) {\n this.classActions['<' + owl_ns + 'FunctionalProperty>'] = [\n function (formula, subj, proj, obj, addFn) {\n return formula.newPropertyAction(subj, handle_FP)\n }\n ] // FP => handleFP, do add to index\n }\n }\n\n /**\n * Adds a triple (quad) to the store.\n *\n * @param {Term} subject - The thing about which the fact a relationship is asserted\n * @param {namedNode} predicate - The relationship which is asserted\n * @param {Term} object - The object of the relationship, e.g. another thing or avalue\n * @param {namedNode} why - The document in which the triple (S,P,O) was or will be stored on the web\n * @returns {Statement} The statement added to the store\n */\n add (subj, pred, obj, why) {\n var i\n if (arguments.length === 1) {\n if (subj instanceof Array) {\n for (i = 0; i < subj.length; i++) {\n this.add(subj[i])\n }\n } else if (subj instanceof Statement) {\n this.add(subj.subject, subj.predicate, subj.object, subj.why)\n } else if (subj instanceof IndexedFormula) {\n this.add(subj.statements)\n }\n return this\n }\n var actions\n var st\n if (!why) {\n // system generated\n why = this.fetcher ? this.fetcher.appNode : this.sym(defaultGraphURI)\n }\n subj = Node.fromValue(subj)\n pred = Node.fromValue(pred)\n obj = Node.fromValue(obj)\n why = Node.fromValue(why)\n if (this.predicateCallback) {\n this.predicateCallback(this, pred, why)\n }\n // Action return true if the statement does not need to be added\n var predHash = this.canon(pred).hashString()\n actions = this.propertyActions[predHash] // Predicate hash\n var done = false\n if (actions) {\n // alert('type: '+typeof actions +' @@ actions='+actions)\n for (i = 0; i < actions.length; i++) {\n done = done || actions[i](this, subj, pred, obj, why)\n }\n }\n if (this.holds(subj, pred, obj, why)) { // Takes time but saves duplicates\n // console.log('rdflib: Ignoring dup! {' + subj + ' ' + pred + ' ' + obj + ' ' + why + '}')\n return null // @@better to return self in all cases?\n }\n // If we are tracking provenance, every thing should be loaded into the store\n // if (done) return new Statement(subj, pred, obj, why)\n // Don't put it in the store\n // still return this statement for owl:sameAs input\n var hash = [ this.canon(subj).hashString(), predHash,\n this.canon(obj).hashString(), this.canon(why).hashString()]\n st = new Statement(subj, pred, obj, why)\n for (i = 0; i < 4; i++) {\n var ix = this.index[i]\n var h = hash[i]\n if (!ix[h]) {\n ix[h] = []\n }\n ix[h].push(st) // Set of things with this as subject, etc\n }\n\n // log.debug(\"ADDING {\"+subj+\" \"+pred+\" \"+obj+\"} \"+why)\n this.statements.push(st)\n return st\n }\n\n addAll (statements) {\n statements.forEach(quad => {\n this.add(quad.subject, quad.predicate, quad.object, quad.graph)\n })\n }\n any (s, p, o, g) {\n var st = this.anyStatementMatching(s, p, o, g)\n if (st == null) {\n return void 0\n } else if (s == null) {\n return st.subject\n } else if (p == null) {\n return st.predicate\n } else if (o == null) {\n return st.object\n }\n return void 0\n }\n\n anyValue (s, p, o, g) {\n var y = this.any(s, p, o, g)\n return y ? y.value : void 0\n }\n\n anyStatementMatching (subj, pred, obj, why) {\n var x = this.statementsMatching(subj, pred, obj, why, true)\n if (!x || x.length === 0) {\n return undefined\n }\n return x[0]\n }\n\n /**\n * Returns the symbol with canonical URI as smushed\n */\n canon (term) {\n if (!term) {\n return term\n }\n var y = this.redirections[term.hashString()]\n if (!y) {\n return term\n }\n return y\n }\n\n check () {\n this.checkStatementList(this.statements)\n for (var p = 0; p < 4; p++) {\n var ix = this.index[p]\n for (var key in ix) {\n if (ix.hasOwnProperty(key)) {\n this.checkStatementList(ix[key], p)\n }\n }\n }\n }\n\n /**\n * Self-consistency checking for diagnostis only\n * Is each statement properly indexed?\n */\n checkStatementList (sts, from) {\n var names = ['subject', 'predicate', 'object', 'why']\n var origin = ' found in ' + names[from] + ' index.'\n var st\n for (var j = 0; j < sts.length; j++) {\n st = sts[j]\n var term = [ st.subject, st.predicate, st.object, st.why ]\n var arrayContains = function (a, x) {\n for (var i = 0; i < a.length; i++) {\n if (a[i].subject.sameTerm(x.subject) &&\n a[i].predicate.sameTerm(x.predicate) &&\n a[i].object.sameTerm(x.object) &&\n a[i].why.sameTerm(x.why)) {\n return true\n }\n }\n }\n for (var p = 0; p < 4; p++) {\n var c = this.canon(term[p])\n var h = c.hashString()\n if (!this.index[p][h]) {\n // throw new Error('No ' + name[p] + ' index for statement ' + st + '@' + st.why + origin)\n } else {\n if (!arrayContains(this.index[p][h], st)) {\n // throw new Error('Index for ' + name[p] + ' does not have statement ' + st + '@' + st.why + origin)\n }\n }\n }\n if (!arrayContains(this.statements, st)) {\n throw new Error('Statement list does not statement ' + st + '@' + st.why + origin)\n }\n }\n }\n\n close () {\n return this\n }\n\n /**\n * replaces @template with @target and add appropriate triples (no triple\n * removed)\n * one-direction replication\n * @method copyTo\n */\n copyTo (template, target, flags) {\n if (!flags) flags = []\n var statList = this.statementsMatching(template)\n if (ArrayIndexOf(flags, 'two-direction') !== -1) {\n statList.concat(this.statementsMatching(undefined, undefined, template))\n }\n for (var i = 0; i < statList.length; i++) {\n var st = statList[i]\n switch (st.object.termType) {\n case 'NamedNode':\n this.add(target, st.predicate, st.object)\n break\n case 'Literal':\n case 'BlankNode':\n case 'Collection':\n this.add(target, st.predicate, st.object.copy(this))\n }\n if (ArrayIndexOf(flags, 'delete') !== -1) {\n this.remove(st)\n }\n }\n }\n\n /**\n * simplify graph in store when we realize two identifiers are equivalent\n * We replace the bigger with the smaller.\n */\n equate (u1, u2) {\n // log.warn(\"Equating \"+u1+\" and \"+u2); // @@\n // @@JAMBO Must canonicalize the uris to prevent errors from a=b=c\n // 03-21-2010\n u1 = this.canon(u1)\n u2 = this.canon(u2)\n var d = u1.compareTerm(u2)\n if (!d) {\n return true // No information in {a = a}\n }\n // var big\n // var small\n if (d < 0) { // u1 less than u2\n return this.replaceWith(u2, u1)\n } else {\n return this.replaceWith(u1, u2)\n }\n }\n\n formula (features) {\n return new IndexedFormula(features)\n }\n\n /**\n * Returns the number of statements contained in this IndexedFormula.\n * (Getter proxy to this.statements).\n * Usage:\n * ```\n * var kb = rdf.graph()\n * kb.length // -> 0\n * ```\n * @return {Number}\n */\n get length () {\n return this.statements.length\n }\n\n /**\n * Returns any quads matching the given arguments.\n * Standard RDFJS Taskforce method for Source objects, implemented as an\n * alias to `statementsMatching()`\n * @method match\n * @param subject {Node|String|Object}\n * @param predicate {Node|String|Object}\n * @param object {Node|String|Object}\n * @param graph {NamedNode|String}\n */\n match (subject, predicate, object, graph) {\n return this.statementsMatching(\n Node.fromValue(subject),\n Node.fromValue(predicate),\n Node.fromValue(object),\n Node.fromValue(graph)\n )\n }\n\n /**\n * Find out whether a given URI is used as symbol in the formula\n */\n mentionsURI (uri) {\n var hash = '<' + uri + '>'\n return (!!this.subjectIndex[hash] ||\n !!this.objectIndex[hash] ||\n !!this.predicateIndex[hash])\n }\n\n // Existentials are BNodes - something exists without naming\n newExistential (uri) {\n if (!uri) return this.bnode()\n var x = this.sym(uri)\n return this.declareExistential(x)\n }\n\n newPropertyAction (pred, action) {\n // log.debug(\"newPropertyAction: \"+pred)\n var hash = pred.hashString()\n if (!this.propertyActions[hash]) {\n this.propertyActions[hash] = []\n }\n this.propertyActions[hash].push(action)\n // Now apply the function to to statements already in the store\n var toBeFixed = this.statementsMatching(undefined, pred, undefined)\n var done = false\n for (var i = 0; i < toBeFixed.length; i++) { // NOT optimized - sort toBeFixed etc\n done = done || action(this, toBeFixed[i].subject, pred, toBeFixed[i].object)\n }\n return done\n }\n\n // Universals are Variables\n newUniversal (uri) {\n var x = this.sym(uri)\n if (!this._universalVariables) this._universalVariables = []\n this._universalVariables.push(x)\n return x\n }\n\n // convenience function used by N3 parser\n variable (name) {\n return new Variable(name)\n }\n\n /**\n * Find an unused id for a file being edited: return a symbol\n * (Note: Slow iff a lot of them -- could be O(log(k)) )\n */\n nextSymbol (doc) {\n for (var i = 0; ;i++) {\n var uri = doc.uri + '#n' + i\n if (!this.mentionsURI(uri)) return this.sym(uri)\n }\n }\n\n query (myQuery, callback, fetcher, onDone) {\n let indexedFormulaQuery = require('./query').indexedFormulaQuery\n return indexedFormulaQuery.call(this, myQuery, callback, fetcher, onDone)\n }\n\n /**\n * Finds a statement object and removes it\n */\n remove (st) {\n if (st instanceof Array) {\n for (var i = 0; i < st.length; i++) {\n this.remove(st[i])\n }\n return this\n }\n if (st instanceof IndexedFormula) {\n return this.remove(st.statements)\n }\n var sts = this.statementsMatching(st.subject, st.predicate, st.object,\n st.why)\n if (!sts.length) {\n throw new Error('Statement to be removed is not on store: ' + st)\n }\n this.removeStatement(sts[0])\n return this\n }\n\n /**\n * Removes all statemnts in a doc\n */\n removeDocument (doc) {\n var sts = this.statementsMatching(undefined, undefined, undefined, doc).slice() // Take a copy as this is the actual index\n for (var i = 0; i < sts.length; i++) {\n this.removeStatement(sts[i])\n }\n return this\n }\n\n /**\n * remove all statements matching args (within limit) *\n */\n removeMany (subj, pred, obj, why, limit) {\n // log.debug(\"entering removeMany w/ subj,pred,obj,why,limit = \" + subj +\", \"+ pred+\", \" + obj+\", \" + why+\", \" + limit)\n var sts = this.statementsMatching(subj, pred, obj, why, false)\n // This is a subtle bug that occcured in updateCenter.js too.\n // The fact is, this.statementsMatching returns this.whyIndex instead of a copy of it\n // but for perfromance consideration, it's better to just do that\n // so make a copy here.\n var statements = []\n for (var i = 0; i < sts.length; i++) statements.push(sts[i])\n if (limit) statements = statements.slice(0, limit)\n for (i = 0; i < statements.length; i++) this.remove(statements[i])\n }\n\n removeMatches (subject, predicate, object, why) {\n this.removeStatements(this.statementsMatching(subject, predicate, object,\n why))\n return this\n }\n\n /**\n * Remove a particular statement object from the store\n *\n * st a statement which is already in the store and indexed.\n * Make sure you only use this for these.\n * Otherwise, you should use remove() above.\n */\n removeStatement (st) {\n // log.debug(\"entering remove w/ st=\" + st)\n var term = [ st.subject, st.predicate, st.object, st.why ]\n for (var p = 0; p < 4; p++) {\n var c = this.canon(term[p])\n var h = c.hashString()\n if (!this.index[p][h]) {\n // log.warn (\"Statement removal: no index '+p+': \"+st)\n } else {\n RDFArrayRemove(this.index[p][h], st)\n }\n }\n RDFArrayRemove(this.statements, st)\n return this\n }\n\n removeStatements (sts) {\n for (var i = 0; i < sts.length; i++) {\n this.remove(sts[i])\n }\n return this\n }\n\n /**\n * Replace big with small, obsoleted with obsoleting.\n */\n replaceWith (big, small) {\n // log.debug(\"Replacing \"+big+\" with \"+small) // @@\n var oldhash = big.hashString()\n var newhash = small.hashString()\n var moveIndex = function (ix) {\n var oldlist = ix[oldhash]\n if (!oldlist) {\n return // none to move\n }\n var newlist = ix[newhash]\n if (!newlist) {\n ix[newhash] = oldlist\n } else {\n ix[newhash] = oldlist.concat(newlist)\n }\n delete ix[oldhash]\n }\n // the canonical one carries all the indexes\n for (var i = 0; i < 4; i++) {\n moveIndex(this.index[i])\n }\n this.redirections[oldhash] = small\n if (big.uri) {\n // @@JAMBO: must update redirections,aliases from sub-items, too.\n if (!this.aliases[newhash]) {\n this.aliases[newhash] = []\n }\n this.aliases[newhash].push(big) // Back link\n if (this.aliases[oldhash]) {\n for (i = 0; i < this.aliases[oldhash].length; i++) {\n this.redirections[this.aliases[oldhash][i].hashString()] = small\n this.aliases[newhash].push(this.aliases[oldhash][i])\n }\n }\n this.add(small, this.sym('http://www.w3.org/2007/ont/link#uri'), big.uri)\n // If two things are equal, and one is requested, we should request the other.\n if (this.fetcher) {\n this.fetcher.nowKnownAs(big, small)\n }\n }\n moveIndex(this.classActions)\n moveIndex(this.propertyActions)\n // log.debug(\"Equate done. \"+big+\" to be known as \"+small)\n return true // true means the statement does not need to be put in\n }\n\n /**\n * Return all equivalent URIs by which this is known\n */\n allAliases (x) {\n var a = this.aliases[this.canon(x).hashString()] || []\n a.push(this.canon(x))\n return a\n }\n\n /**\n * Compare by canonical URI as smushed\n */\n sameThings (x, y) {\n if (x.sameTerm(y)) {\n return true\n }\n var x1 = this.canon(x)\n // alert('x1='+x1)\n if (!x1) return false\n var y1 = this.canon(y)\n // alert('y1='+y1); //@@\n if (!y1) return false\n return (x1.uri === y1.uri)\n }\n\n setPrefixForURI (prefix, nsuri) {\n // TODO: This is a hack for our own issues, which ought to be fixed\n // post-release\n // See http://dig.csail.mit.edu/cgi-bin/roundup.cgi/$rdf/issue227\n if (prefix === 'tab' && this.namespaces['tab']) {\n return\n } // There are files around with long badly generated prefixes like this\n if (prefix.slice(0, 2) === 'ns' || prefix.slice(0, 7) === 'default') {\n return\n }\n this.namespaces[prefix] = nsuri\n }\n\n /**\n * Return statements matching a pattern\n * ALL CONVENIENCE LOOKUP FUNCTIONS RELY ON THIS!\n */\n statementsMatching (subj, pred, obj, why, justOne) {\n // log.debug(\"Matching {\"+subj+\" \"+pred+\" \"+obj+\"}\")\n var pat = [ subj, pred, obj, why ]\n var pattern = []\n var hash = []\n var wild = [] // wildcards\n var given = [] // Not wild\n var p\n var list\n for (p = 0; p < 4; p++) {\n pattern[p] = this.canon(Node.fromValue(pat[p]))\n if (!pattern[p]) {\n wild.push(p)\n } else {\n given.push(p)\n hash[p] = pattern[p].hashString()\n }\n }\n if (given.length === 0) {\n return this.statements\n }\n if (given.length === 1) { // Easy too, we have an index for that\n p = given[0]\n list = this.index[p][hash[p]]\n if (list && justOne) {\n if (list.length > 1) {\n list = list.slice(0, 1)\n }\n }\n list = list || []\n return list\n }\n // Now given.length is 2, 3 or 4.\n // We hope that the scale-free nature of the data will mean we tend to get\n // a short index in there somewhere!\n var best = 1e10 // really bad\n var best_i\n var i\n for (i = 0; i < given.length; i++) {\n p = given[i] // Which part we are dealing with\n list = this.index[p][hash[p]]\n if (!list) {\n return [] // No occurrences\n }\n if (list.length < best) {\n best = list.length\n best_i = i // (not p!)\n }\n }\n // Ok, we have picked the shortest index but now we have to filter it\n var best_p = given[best_i]\n var possibles = this.index[best_p][hash[best_p]]\n var check = given.slice(0, best_i).concat(given.slice(best_i + 1)) // remove best_i\n var results = []\n var parts = [ 'subject', 'predicate', 'object', 'why' ]\n for (var j = 0; j < possibles.length; j++) {\n var st = possibles[j]\n\n for (i = 0; i < check.length; i++) { // for each position to be checked\n p = check[i]\n if (!this.canon(st[parts[p]]).sameTerm(pattern[p])) {\n st = null\n break\n }\n }\n if (st != null) {\n results.push(st)\n if (justOne) break\n }\n }\n return results\n }\n\n /**\n * A list of all the URIs by which this thing is known\n */\n uris (term) {\n var cterm = this.canon(term)\n var terms = this.aliases[cterm.hashString()]\n if (!cterm.uri) return []\n var res = [ cterm.uri ]\n if (terms) {\n for (var i = 0; i < terms.length; i++) {\n res.push(terms[i].uri)\n }\n }\n return res\n }\n}\nmodule.exports = IndexedFormula\nIndexedFormula.handleRDFType = handleRDFType\n","const NamedNode = require('./named-node')\n\nfunction Namespace (nsuri) {\n return function (ln) {\n return new NamedNode(nsuri + (ln || ''))\n }\n}\n\nmodule.exports = Namespace\n","'use strict'\nconst BlankNode = require('./blank-node')\nconst ClassOrder = require('./class-order')\nconst Node = require('./node')\n\nclass Collection extends Node {\n constructor (initial) {\n super()\n this.termType = Collection.termType\n this.id = BlankNode.nextId++\n this.elements = []\n this.closed = false\n if (initial && initial.length > 0) {\n initial.forEach(element => {\n this.elements.push(Node.fromValue(element))\n })\n }\n }\n append (element) {\n return this.elements.push(element)\n }\n close () {\n this.closed = true\n return this.closed\n }\n shift () {\n return this.elements.shift()\n }\n substitute (bindings) {\n var elementsCopy = this.elements.map(function (ea) {\n ea.substitute(bindings)\n })\n return new Collection(elementsCopy)\n }\n toNT () {\n return BlankNode.NTAnonymousNodePrefix + this.id\n }\n toString () {\n return '(' + this.elements.join(' ') + ')'\n }\n unshift (element) {\n return this.elements.unshift(element)\n }\n}\nCollection.termType = 'Collection'\nCollection.prototype.classOrder = ClassOrder['Collection']\nCollection.prototype.compareTerm = BlankNode.prototype.compareTerm\nCollection.prototype.isVar = 0\n\nmodule.exports = Collection\n","'use strict';\n\nif (!process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict'\nconst BlankNode = require('./blank-node')\nconst Collection = require('./collection')\nconst DefaultGraph = require('./default-graph')\nconst Fetcher = require('./fetcher')\nconst IndexedFormula = require('./indexed-formula')\nconst Literal = require('./literal')\nconst NamedNode = require('./named-node')\nconst Statement = require('./statement')\nconst Variable = require('./variable')\n\nfunction blankNode (value) {\n return new BlankNode(value)\n}\nfunction collection (elements) {\n return new Collection(elements)\n}\nfunction defaultGraph () {\n return new DefaultGraph()\n}\nfunction fetcher (store, options) {\n return new Fetcher(store, options)\n}\nfunction graph () {\n return new IndexedFormula()\n}\nfunction lit (val, lang, dt) {\n return new Literal('' + val, lang, dt)\n}\nfunction literal (value, languageOrDatatype) {\n if (typeof languageOrDatatype === 'string') {\n if (languageOrDatatype.indexOf(':') === -1) {\n return new Literal(value, languageOrDatatype)\n } else {\n return new Literal(value, null, namedNode(languageOrDatatype))\n }\n } else {\n return new Literal(value, null, languageOrDatatype)\n }\n}\nfunction namedNode (value) {\n return new NamedNode(value)\n}\nfunction quad (subject, predicate, object, graph) {\n graph = graph || new DefaultGraph()\n return new Statement(subject, predicate, object, graph)\n}\nfunction st (subject, predicate, object, graph) {\n return new Statement(subject, predicate, object, graph)\n}\nfunction triple (subject, predicate, object) {\n return quad(subject, predicate, object)\n}\nfunction variable (name) {\n return new Variable(name)\n}\n\n// rdfjs spec factory methods\nmodule.exports.blankNode = blankNode\nmodule.exports.defaultGraph = defaultGraph\nmodule.exports.graph = graph\nmodule.exports.literal = literal\nmodule.exports.namedNode = namedNode\nmodule.exports.quad = quad\nmodule.exports.triple = triple\nmodule.exports.variable = variable\n\n// rdflib only\nmodule.exports.collection = collection\nmodule.exports.fetcher = fetcher\nmodule.exports.lit = lit\nmodule.exports.st = st\n","'use strict'\nconst Node = require('./node')\n\nclass Statement {\n /* Construct a new statment\n **\n ** @param {Term} subject - The subject of the triple. What the efact is about\n ** @ param {Term} predciate - The relationship which is assrted between the subject and object\n ** @param {Term} object - The thing or data value which is asserted to be related to the subject\n ** @param {NamedNode} why - The document where thr triple is or was or will be stored on the web.\n **\n ** The why param is a named node of the document in which the triple when\n ** it is stored on the web.\n ** It is called “why” because when you have read data from varou slaces the\n ** “why” tells you why you have the triple. (At the moment, it is just the\n ** document, in future it could be an inference step). When you do\n ** UpdateManager.update() then the why’s of all the statmemts must be the same,\n ** and give the document you are patching. In future, we may have a more\n ** powerful update() which can update more than one docment.\n */\n constructor (subject, predicate, object, graph) {\n this.subject = Node.fromValue(subject)\n this.predicate = Node.fromValue(predicate)\n this.object = Node.fromValue(object)\n this.why = graph // property currently used by rdflib\n }\n get graph () {\n return this.why\n }\n set graph (g) {\n this.why = g\n }\n equals (other) {\n return other.subject.equals(this.subject) && other.predicate.equals(this.predicate) &&\n other.object.equals(this.object) && other.graph.equals(this.graph)\n }\n substitute (bindings) {\n const y = new Statement(\n this.subject.substitute(bindings),\n this.predicate.substitute(bindings),\n this.object.substitute(bindings),\n this.why.substitute(bindings)) // 2016\n console.log('@@@ statement substitute:' + y)\n return y\n }\n toCanonical () {\n let terms = [\n this.subject.toCanonical(),\n this.predicate.toCanonical(),\n this.object.toCanonical()\n ]\n if (this.graph && this.graph.termType !== 'DefaultGraph') {\n terms.push(this.graph.toCanonical())\n }\n return terms.join(' ') + ' .'\n }\n toNT () {\n return [this.subject.toNT(), this.predicate.toNT(),\n this.object.toNT()].join(' ') + ' .'\n }\n toString () {\n return this.toNT()\n }\n}\n\nmodule.exports = Statement\n","'use strict'\nconst ClassOrder = require('./class-order')\nconst Node = require('./node')\nconst Uri = require('./uri')\n\n/**\n * Variables are placeholders used in patterns to be matched.\n * In cwm they are symbols which are the formula's list of quantified variables.\n * In sparql they are not visibly URIs. Here we compromise, by having\n * a common special base URI for variables. Their names are uris,\n * but the ? notation has an implicit base uri of 'varid:'\n * @class Variable\n */\nclass Variable extends Node {\n constructor (name = '') {\n super()\n this.termType = Variable.termType\n this.value = name\n this.base = 'varid:'\n this.uri = Uri.join(name, this.base)\n }\n equals (other) {\n if (!other) {\n return false\n }\n return (this.termType === other.termType) && (this.value === other.value)\n }\n hashString () {\n return this.toString()\n }\n substitute (bindings) {\n var ref\n return (ref = bindings[this.toNT()]) != null ? ref : this\n }\n toString () {\n if (this.uri.slice(0, this.base.length) === this.base) {\n return '?' + this.uri.slice(this.base.length)\n }\n return '?' + this.uri\n }\n}\n\nVariable.termType = 'Variable'\nVariable.prototype.classOrder = ClassOrder['Variable']\nVariable.prototype.isVar = 1\n\nmodule.exports = Variable\n","// Matching a formula against another formula\n// Assync as well as Synchronously\n//\n// W3C open source licence 2005.\n//\n// This builds on term.js, match.js (and identity.js?)\n// to allow a query of a formula.\n//\n// Here we introduce for the first time a subclass of term: variable.\n//\n// SVN ID: $Id: query.js 25116 2008-11-15 16:13:48Z timbl $\n\n// Variable\n//\n// Compare with BlankNode. They are similar, but a variable\n// stands for something whose value is to be returned.\n// Also, users name variables and want the same name back when stuff is printed\n/* jsl:option explicit*/ // Turn on JavaScriptLint variable declaration checking\n\nconst IndexedFormula = require('./indexed-formula')\nconst log = require('./log')\nconst docpart = require('./uri').docpart\n\nconst defaultDocumentURI = IndexedFormula.defaultGraphURI\n/**\n * Query class, for tracking queries the user has in the UI.\n */\nclass Query {\n constructor (name, id) {\n this.pat = new IndexedFormula() // The pattern to search for\n this.vars = [] // Used by UI code but not in query.js\n // this.orderBy = [] // Not used yet\n this.name = name\n this.id = id\n }\n}\n\n/**\n * This function will match a pattern to the current kb\n *\n * The callback function is called whenever a match is found\n * When fetcher is supplied this will be called to satisfy any resource requests\n * currently not in the kb. The fetcher function needs to be defined manualy and\n * should call $rdf.Util.AJAR_handleNewTerm to process the requested resource.\n *\n * @param\tmyQuery,\ta knowledgebase containing a pattern to use as query\n * @param\tcallback, \twhenever the pattern in myQuery is met this is called with\n * \t\t\t\t\t\tthe new bindings as parameter\n * @param\tfetcher,\twhenever a resource needs to be loaded this gets called IGNORED OBSOLETE\n * f.fetecher is used as a Fetcher instance to do this.\n * @param onDone callback when\n */\nfunction indexedFormulaQuery (myQuery, callback, fetcher, onDone) {\n // var kb = this\n // /////////// Debug strings\n var bindingDebug = function (b) {\n var str = ''\n var v\n for (v in b) {\n if (b.hasOwnProperty(v)) {\n str += ' ' + v + ' -> ' + b[v]\n }\n }\n return str\n }\n\n var bindingsDebug = function (nbs) {\n var str = 'Bindings: '\n var i\n var n = nbs.length\n for (i = 0; i < n; i++) {\n str += bindingDebug(nbs[i][0]) + ';\\n\\t'\n }\n return str\n } // bindingsDebug\n\n // Unification: see also\n // http://www.w3.org/2000/10/swap/term.py\n // for similar things in python\n //\n // Unification finds all bindings such that when the binding is applied\n // to one term it is equal to the other.\n // Returns: a list of bindings, where a binding is an associative array\n // mapping variuable to value.\n\n var unifyTerm = function (self, other, bindings, formula) {\n var actual = bindings[self]\n if (actual === undefined) { // Not mapped\n if (self.isVar) {\n /* if (self.isBlank) //bnodes are existential variables\n {\n if (self.toString() == other.toString()) return [[ [], null]]\n else return []\n }*/\n var b = []\n b[self] = other\n return [[ b, null ]] // Match\n }\n actual = self\n }\n if (!actual.complexType) {\n if (formula.redirections[actual]) {\n actual = formula.redirections[actual]\n }\n if (formula.redirections[other]) {\n other = formula.redirections[other]\n }\n if (actual.sameTerm(other) || (actual.uri && actual.uri === defaultDocumentURI)) { // Used to mean 'any graph' in a query\n return [[ [], null ]]\n }\n return []\n }\n if (self instanceof Array) {\n if (!(other instanceof Array)) {\n return []\n }\n return unifyContents(self, other, bindings)\n }\n throw new Error('query.js: oops - code not written yet')\n // return undefined; // for lint - no jslint objects to unreachables\n // return actual.unifyContents(other, bindings)\n } // unifyTerm\n\n var unifyContents = function (self, other, bindings, formula) {\n var nbs2\n if (self.length !== other.length) {\n return [] // no way\n }\n if (!self.length) {\n return [[ [], null ]] // Success\n }\n var nbs = unifyTerm(self[0], other[0], bindings, formula)\n if (nbs.length === 0) {\n return nbs\n }\n var res = []\n var i\n var n = nbs.length\n var nb\n var j\n var m\n var v\n var nb2\n var bindings2\n for (i = 0; i < n; i++) { // for each possibility from the first term\n nb = nbs[i][0] // new bindings\n bindings2 = []\n for (v in nb) {\n if (nb.hasOwnProperty(v)) {\n bindings2[v] = nb[v] // copy\n }\n }\n for (v in bindings) {\n if (bindings.hasOwnProperty(v)) {\n bindings2[v] = bindings[v] // copy\n }\n }\n nbs2 = unifyContents(self.slice(1), other.slice(1), bindings2, formula)\n m = nbs2.length\n for (j = 0; j < m; j++) {\n nb2 = nbs2[j][0] // @@@@ no idea whether this is used or right\n for (v in nb) {\n if (nb.hasOwnProperty(v)) {\n nb2[v] = nb[v]\n }\n }\n res.push([nb2, null])\n }\n }\n return res\n } // unifyContents\n\n // Matching\n //\n // Matching finds all bindings such that when the binding is applied\n // to one term it is equal to the other term. We only match formulae.\n\n /** if x is not in the bindings array, return the var; otherwise, return the bindings **/\n var bind = function (x, binding) {\n var y = binding[x]\n if (y === undefined) {\n return x\n }\n return y\n }\n\n // When there are OPTIONAL clauses, we must return bindings without them if none of them\n // succeed. However, if any of them do succeed, we should not. (This is what branchCount()\n // tracked. The problem currently is (2011/7) that when several optionals exist, and they\n // all match, multiple sets of bindings are returned, each with one optional filled in.)\n\n var union = function (a, b) {\n var c = {}\n var x\n for (x in a) {\n if (a.hasOwnProperty(x)) {\n c[x] = a[x]\n }\n }\n for (x in b) {\n if (b.hasOwnProperty(x)) {\n c[x] = b[x]\n }\n }\n return c\n }\n\n var OptionalBranchJunction = function (originalCallback, trunkBindings) {\n this.trunkBindings = trunkBindings\n this.originalCallback = originalCallback\n this.branches = []\n // this.results = []; // result[i] is an array of bindings for branch i\n // this.done = {}; // done[i] means all/any results are in for branch i\n // this.count = {}\n return this\n }\n\n OptionalBranchJunction.prototype.checkAllDone = function () {\n var i\n for (i = 0; i < this.branches.length; i++) {\n if (!this.branches[i].done) {\n return\n }\n }\n log.debug('OPTIONAL BIDNINGS ALL DONE:')\n this.doCallBacks(this.branches.length - 1, this.trunkBindings)\n }\n // Recrursively generate the cross product of the bindings\n OptionalBranchJunction.prototype.doCallBacks = function (b, bindings) {\n var j\n if (b < 0) {\n return this.originalCallback(bindings)\n }\n for (j = 0; j < this.branches[b].results.length; j++) {\n this.doCallBacks(b - 1, union(bindings, this.branches[b].results[j]))\n }\n }\n\n // A mandatory branch is the normal one, where callbacks\n // are made immediately and no junction is needed.\n // Might be useful for onFinsihed callback for query API.\n var MandatoryBranch = function (callback, onDone) {\n this.count = 0\n this.success = false\n this.done = false\n // this.results = []\n this.callback = callback\n this.onDone = onDone\n // this.junction = junction\n // junction.branches.push(this)\n return this\n }\n\n MandatoryBranch.prototype.reportMatch = function (bindings) {\n // log.error(\"@@@@ query.js 1\"); // @@\n this.callback(bindings)\n this.success = true\n }\n\n MandatoryBranch.prototype.reportDone = function () {\n this.done = true\n log.info('Mandatory query branch finished.***')\n if (this.onDone !== undefined) {\n this.onDone()\n }\n }\n\n // An optional branch hoards its results.\n var OptionalBranch = function (junction) {\n this.count = 0\n this.done = false\n this.results = []\n this.junction = junction\n junction.branches.push(this)\n return this\n }\n\n OptionalBranch.prototype.reportMatch = function (bindings) {\n this.results.push(bindings)\n }\n\n OptionalBranch.prototype.reportDone = function () {\n log.debug('Optional branch finished - results.length = ' + this.results.length)\n if (this.results.length === 0) { // This is what optional means: if no hits,\n this.results.push({}) // mimic success, but with no bindings\n log.debug(\"Optional branch FAILED - that's OK.\")\n }\n this.done = true\n this.junction.checkAllDone()\n }\n\n /** prepare -- sets the index of the item to the possible matches\n * @param f - formula\n * @param item - an Statement, possibly w/ vars in it\n * @param bindings - Bindings so far\n * @returns false if the query fails -- there are no items that match **/\n var prepare = function (f, item, bindings) {\n var terms, termIndex, i, ind\n item.nvars = 0\n item.index = null\n // if (!f.statements) log.warn(\"@@@ prepare: f is \"+f)\n // log.debug(\"Prepare: f has \"+ f.statements.length)\n // log.debug(\"Prepare: Kb size \"+f.statements.length+\" Preparing \"+item)\n\n terms = [item.subject, item.predicate, item.object, item.why]\n ind = [f.subjectIndex, f.predicateIndex, f.objectIndex, f.whyIndex]\n for (i = 0; i < 4; i++) {\n let t = terms[i]\n // console.log(\" Prepare (\" + t + \") \"+(t in bindings))\n if (t.uri && t.uri === defaultDocumentURI) { // chrome:session\n // console.log(' query: Ignoring slot ' + i)\n } else if (t.isVar && !(bindings[t] !== undefined)) {\n item.nvars++\n } else {\n t = bind(terms[i], bindings) // returns the RDF binding if bound, otherwise itself\n // if (terms[i]!=bind(terms[i],bindings) alert(\"Term: \"+terms[i]+\"Binding: \"+bind(terms[i], bindings))\n if (f.redirections[t.hashString()]) {\n t = f.redirections[t.hashString()] // redirect\n }\n termIndex = ind[i][t.hashString()]\n\n if (!termIndex) {\n item.index = []\n return false // Query line cannot match\n }\n if ((item.index === null) || (item.index.length > termIndex.length)) { // Find smallest index\n item.index = termIndex\n }\n }\n }\n\n if (item.index === null) { // All 4 are variables?\n item.index = f.statements\n }\n return true\n } // prepare\n\n /** sorting function -- negative if self is easier **/\n // We always prefer to start with a URI to be able to browse a graph\n // this is why we put off items with more variables till later.\n function easiestQuery (self, other) {\n if (self.nvars !== other.nvars) {\n return self.nvars - other.nvars\n }\n return self.index.length - other.index.length\n }\n\n var match_index = 0 // index\n /** matches a pattern formula against the knowledge base, e.g. to find matches for table-view\n *\n * @param f - knowledge base formula\n * @param g - pattern formula (may have vars)\n * @param bindingsSoFar - bindings accumulated in matching to date\n * @param level - spaces to indent stuff also lets you know what level of recursion you're at\n * @param fetcher - function (term, requestedBy) - myFetcher / AJAR_handleNewTerm / the sort\n * @param localCallback - function(bindings, pattern, branch) called on sucess\n * @returns nothing\n *\n * Will fetch linked data from the web iff the knowledge base an associated source fetcher (f.fetcher)\n ***/\n var match = function (f, g, bindingsSoFar, level, fetcher, localCallback, branch) {\n log.debug('Match begins, Branch count now: ' + branch.count + ' for ' + branch.pattern_debug)\n var sf = f.fetcher ? f.fetcher : null\n // log.debug(\"match: f has \"+f.statements.length+\", g has \"+g.statements.length)\n var pattern = g.statements\n if (pattern.length === 0) { // when it's satisfied all the pattern triples\n log.debug('FOUND MATCH WITH BINDINGS:' + bindingDebug(bindingsSoFar))\n if (g.optional.length === 0) {\n branch.reportMatch(bindingsSoFar)\n } else {\n log.debug('OPTIONAL: ' + g.optional)\n var junction = new OptionalBranchJunction(callback, bindingsSoFar) // @@ won't work with nested optionals? nest callbacks\n var br = []\n var b\n for (b = 0; b < g.optional.length; b++) {\n br[b] = new OptionalBranch(junction) // Allocate branches to prevent premature ending\n br[b].pattern_debug = g.optional[b] // for diagnotics only\n }\n for (b = 0; b < g.optional.length; b++) {\n br[b].count = br[b].count + 1 // Count how many matches we have yet to complete\n match(f, g.optional[b], bindingsSoFar, '', fetcher, callback, br[b])\n }\n }\n branch.count--\n log.debug('Match ends -- success , Branch count now: ' + branch.count + ' for ' + branch.pattern_debug)\n return // Success\n }\n\n var item\n var i\n var n = pattern.length\n // log.debug(level + \"Match \"+n+\" left, bs so far:\"+bindingDebug(bindingsSoFar))\n\n // Follow links from variables in query\n if (sf) { // Fetcher is used to fetch URIs, function first term is a URI term, second is the requester\n var id = 'match' + match_index++\n var fetchResource = function (requestedTerm, id) {\n var docuri = requestedTerm.uri.split('#')[0]\n sf.nowOrWhenFetched(docuri, undefined, function (ok, body, xhr) {\n if (!ok) {\n console.log('Error following link to <' + requestedTerm.uri + '> in query: ' + body)\n }\n match(f, g, bindingsSoFar, level, fetcher, // match not match2 to look up any others necessary.\n localCallback, branch)\n })\n }\n for (i = 0; i < n; i++) {\n item = pattern[i] // for each of the triples in the query\n if (bindingsSoFar[item.subject] !== undefined &&\n bindingsSoFar[item.subject].uri && sf &&\n sf.getState(docpart(bindingsSoFar[item.subject].uri)) === 'unrequested') {\n // fetch the subject info and return to id\n fetchResource(bindingsSoFar[item.subject], id)\n return // only look up one per line this time, but we will come back again though match\n }\n if (bindingsSoFar[item.object] !== undefined &&\n bindingsSoFar[item.object].uri && sf &&\n sf.getState(docpart(bindingsSoFar[item.object].uri)) === 'unrequested') {\n fetchResource(bindingsSoFar[item.object], id)\n return\n }\n }\n } // if sf\n match2(f, g, bindingsSoFar, level, fetcher, localCallback, branch)\n return\n } // match\n\n var constraintsSatisfied = function (bindings, constraints) {\n var res = true\n var x\n var test\n for (x in bindings) {\n if (bindings.hasOwnProperty(x)) {\n if (constraints[x]) {\n test = constraints[x].test\n if (test && !test(bindings[x])) {\n res = false\n }\n }\n }\n }\n return res\n }\n\n /** match2 -- stuff after the fetch **/\n var match2 = function (f, g, bindingsSoFar, level, fetcher, callback, branch) { // post fetch\n var pattern = g.statements\n var n = pattern.length\n var i\n var k\n var nk\n var v\n var bindings2\n var newBindings1\n var item\n for (i = 0; i < n; i++) { // For each statement left in the query, run prepare\n item = pattern[i]\n // log.info('match2: item=' + item + ', bindingsSoFar=' + bindingDebug(bindingsSoFar))\n prepare(f, item, bindingsSoFar)\n // if (item.index) console.log(' item.index.length ' + item.index.length)\n }\n pattern.sort(easiestQuery)\n item = pattern[0]\n // log.debug(\"Sorted pattern:\\n\"+pattern)\n var rest = f.formula()\n rest.optional = g.optional\n rest.constraints = g.constraints\n rest.statements = pattern.slice(1) // No indexes: we will not query g.\n log.debug(level + 'match2 searching ' + item.index.length + ' for ' + item +\n '; bindings so far=' + bindingDebug(bindingsSoFar))\n // var results = []\n var c\n var nc = item.index.length\n var nbs1\n var st\n var onward = 0\n // var x\n for (c = 0; c < nc; c++) { // For each candidate statement\n st = item.index[c] // for each statement in the item's index, spawn a new match with that binding\n nbs1 = unifyContents(\n [item.subject, item.predicate, item.object, item.why],\n [st.subject, st.predicate, st.object, st.why], bindingsSoFar, f)\n log.info(level + ' From first: ' + nbs1.length + ': ' + bindingsDebug(nbs1))\n nk = nbs1.length\n // branch.count += nk\n // log.debug(\"Branch count bumped \"+nk+\" to: \"+branch.count)\n for (k = 0; k < nk; k++) { // For each way that statement binds\n bindings2 = []\n newBindings1 = nbs1[k][0]\n if (!constraintsSatisfied(newBindings1, g.constraints)) {\n // branch.count--\n log.debug('Branch count CS: ' + branch.count)\n } else {\n for (v in newBindings1) {\n if (newBindings1.hasOwnProperty(v)) {\n bindings2[v] = newBindings1[v] // copy\n }\n }\n for (v in bindingsSoFar) {\n if (bindingsSoFar.hasOwnProperty(v)) {\n bindings2[v] = bindingsSoFar[v] // copy\n }\n }\n\n branch.count++ // Count how many matches we have yet to complete\n onward++\n match(f, rest, bindings2, level + ' ', fetcher, callback, branch) // call match\n }\n }\n }\n branch.count--\n if (onward === 0) {\n log.debug('Match2 fails completely on ' + item)\n }\n log.debug('Match2 ends, Branch count: ' + branch.count + ' for ' + branch.pattern_debug)\n if (branch.count === 0) {\n log.debug('Branch finished.')\n branch.reportDone()\n }\n } // match2\n // ////////////////////////// Body of query() ///////////////////////\n /*\n if(!fetcher) {\n fetcher=function (x, requestedBy) {\n if (x === null) {\n return\n }\n $rdf.Util.AJAR_handleNewTerm(kb, x, requestedBy)\n }\n }\n */\n // prepare, oncallback: match1\n // match1: fetcher, oncallback: match2\n // match2, oncallback: populatetable\n // log.debug(\"Query F length\"+this.statements.length+\" G=\"+myQuery)\n var f = this\n log.debug('Query on ' + this.statements.length)\n // kb.remoteQuery(myQuery,'http://jena.hpl.hp.com:3040/backstage',callback)\n // return\n var trunck = new MandatoryBranch(callback, onDone)\n trunck.count++ // count one branch to complete at the moment\n setTimeout(function () {\n match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback,\n trunck /* branch */)\n }, 0)\n\n return // returns nothing; callback does the work\n} // query\n\nmodule.exports.Query = Query\nmodule.exports.indexedFormulaQuery = indexedFormulaQuery\n","// **N3Lexer** tokenizes N3 documents.\nvar fromCharCode = String.fromCharCode;\nvar immediately = typeof setImmediate === 'function' ? setImmediate :\n function setImmediate(func) { setTimeout(func, 0); };\n\n// Regular expression and replacement string to escape N3 strings.\n// Note how we catch invalid unicode sequences separately (they will trigger an error).\nvar escapeSequence = /\\\\u([a-fA-F0-9]{4})|\\\\U([a-fA-F0-9]{8})|\\\\[uU]|\\\\(.)/g;\nvar escapeReplacements = { '\\\\': '\\\\', \"'\": \"'\", '\"': '\"',\n 'n': '\\n', 'r': '\\r', 't': '\\t', 'f': '\\f', 'b': '\\b',\n '_': '_', '~': '~', '.': '.', '-': '-', '!': '!', '$': '$', '&': '&',\n '(': '(', ')': ')', '*': '*', '+': '+', ',': ',', ';': ';', '=': '=',\n '/': '/', '?': '?', '#': '#', '@': '@', '%': '%' };\nvar illegalIriChars = /[\\x00-\\x20<>\\\\\"\\{\\}\\|\\^\\`]/;\n\n// ## Constructor\nfunction N3Lexer(options) {\n if (!(this instanceof N3Lexer))\n return new N3Lexer(options);\n\n // In line mode (N-Triples or N-Quads), only simple features may be parsed\n if (options && options.lineMode) {\n // Don't tokenize special literals\n this._tripleQuotedString = this._number = this._boolean = /$0^/;\n // Swap the tokenize method for a restricted version\n var self = this;\n this._tokenize = this.tokenize;\n this.tokenize = function (input, callback) {\n this._tokenize(input, function (error, token) {\n if (!error && /^(?:IRI|prefixed|literal|langcode|type|\\.|eof)$/.test(token.type))\n callback && callback(error, token);\n else\n callback && callback(error || self._syntaxError(token.type, callback = null));\n });\n };\n }\n}\n\nN3Lexer.prototype = {\n // ## Regular expressions\n // It's slightly faster to have these as properties than as in-scope variables.\n\n _iri: /^<((?:[^>\\\\]|\\\\[uU])+)>/, // IRI with escape sequences; needs sanity check after unescaping\n _unescapedIri: /^<([^\\x00-\\x20<>\\\\\"\\{\\}\\|\\^\\`]*)>/, // IRI without escape sequences; no unescaping\n _unescapedString: /^\"[^\"\\\\]+\"(?=[^\"\\\\])/, // non-empty string without escape sequences\n _singleQuotedString: /^\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"(?=[^\"\\\\])|^'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'(?=[^'\\\\])/,\n _tripleQuotedString: /^\"\"(\"[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\")\"\"|^''('[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*')''/,\n _langcode: /^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\\-])/i,\n _prefix: /^((?:[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]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:\\.?[\\-0-9A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)?:(?=[#\\s<])/,\n _prefixed: /^((?:[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]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:\\.?[\\-0-9A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)?:((?:(?:[0-: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]|[\\ud800-\\udb7f][\\udc00-\\udfff]|%[0-9a-fA-F]{2}|\\\\[!#-\\/;=?\\-@_~])(?:(?:[\\.\\-0-:A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff]|%[0-9a-fA-F]{2}|\\\\[!#-\\/;=?\\-@_~])*(?:[\\-0-:A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff]|%[0-9a-fA-F]{2}|\\\\[!#-\\/;=?\\-@_~]))?)?)(?=\\.?[,;\\s#()\\[\\]\\{\\}\"'<])/,\n _blank: /^_:((?:[0-9A-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]|[\\ud800-\\udb7f][\\udc00-\\udfff])(?:\\.?[\\-0-9A-Z_a-z\\xb7\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u037d\\u037f-\\u1fff\\u200c\\u200d\\u203f\\u2040\\u2070-\\u218f\\u2c00-\\u2fef\\u3001-\\ud7ff\\uf900-\\ufdcf\\ufdf0-\\ufffd]|[\\ud800-\\udb7f][\\udc00-\\udfff])*)(?=\\.?[,;:\\s#()\\[\\]\\{\\}\"'<])/,\n _number: /^[\\-+]?(?:\\d+\\.?\\d*([eE](?:[\\-\\+])?\\d+)|\\d*\\.?\\d+)(?=[.,;:\\s#()\\[\\]\\{\\}\"'<])/,\n _boolean: /^(?:true|false)(?=[.,;:\\s#()\\[\\]\\{\\}\"'<])/,\n _keyword: /^@[a-z]+(?=[\\s#<:])/,\n _sparqlKeyword: /^(?:PREFIX|BASE|GRAPH)(?=[\\s#<:])/i,\n _shortPredicates: /^a(?=\\s+|<)/,\n _newline: /^[ \\t]*(?:#[^\\n\\r]*)?(?:\\r\\n|\\n|\\r)[ \\t]*/,\n _whitespace: /^[ \\t]+/,\n _endOfFile: /^(?:#[^\\n\\r]*)?$/,\n\n // ## Private methods\n\n // ### `_tokenizeToEnd` tokenizes as for as possible, emitting tokens through the callback.\n _tokenizeToEnd: function (callback, inputFinished) {\n // Continue parsing as far as possible; the loop will return eventually.\n var input = this._input;\n while (true) {\n // Count and skip whitespace lines.\n var whiteSpaceMatch;\n while (whiteSpaceMatch = this._newline.exec(input))\n input = input.substr(whiteSpaceMatch[0].length, input.length), this._line++;\n // Skip whitespace on current line.\n if (whiteSpaceMatch = this._whitespace.exec(input))\n input = input.substr(whiteSpaceMatch[0].length, input.length);\n\n // Stop for now if we're at the end.\n if (this._endOfFile.test(input)) {\n // If the input is finished, emit EOF.\n if (inputFinished)\n callback(input = null, { line: this._line, type: 'eof', value: '', prefix: '' });\n return this._input = input;\n }\n\n // Look for specific token types based on the first character.\n var line = this._line, type = '', value = '', prefix = '',\n firstChar = input[0], match = null, matchLength = 0, unescaped, inconclusive = false;\n switch (firstChar) {\n case '^':\n // Try to match a type.\n if (input.length === 1) break;\n else if (input[1] !== '^') return reportSyntaxError(this);\n this._prevTokenType = '^';\n // Move to type IRI or prefixed name.\n input = input.substr(2);\n if (input[0] !== '<') {\n inconclusive = true;\n break;\n }\n // Fall through in case the type is an IRI.\n\n case '<':\n // Try to find a full IRI without escape sequences.\n if (match = this._unescapedIri.exec(input))\n type = 'IRI', value = match[1];\n // Try to find a full IRI with escape sequences.\n else if (match = this._iri.exec(input)) {\n unescaped = this._unescape(match[1]);\n if (unescaped === null || illegalIriChars.test(unescaped))\n return reportSyntaxError(this);\n type = 'IRI', value = unescaped;\n }\n break;\n\n case '_':\n // Try to find a blank node. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a prefixed name.\n // Therefore, try inserting a space if we're at the end of the input.\n if ((match = this._blank.exec(input)) ||\n inputFinished && (match = this._blank.exec(input + ' ')))\n type = 'prefixed', prefix = '_', value = match[1];\n break;\n\n case '\"':\n case \"'\":\n // Try to find a non-empty double-quoted literal without escape sequences.\n if (match = this._unescapedString.exec(input))\n type = 'literal', value = match[0];\n // Try to find any other literal wrapped in a pair of single or double quotes.\n else if (match = this._singleQuotedString.exec(input)) {\n unescaped = this._unescape(match[0]);\n if (unescaped === null)\n return reportSyntaxError(this);\n type = 'literal', value = unescaped.replace(/^'|'$/g, '\"');\n }\n // Try to find a literal wrapped in three pairs of single or double quotes.\n else if (match = this._tripleQuotedString.exec(input)) {\n unescaped = match[1] || match[2];\n // Count the newlines and advance line counter.\n this._line += unescaped.split(/\\r\\n|\\r|\\n/).length - 1;\n unescaped = this._unescape(unescaped);\n if (unescaped === null)\n return reportSyntaxError(this);\n type = 'literal', value = unescaped.replace(/^'|'$/g, '\"');\n }\n break;\n\n case '@':\n // Try to find a language code.\n if (this._prevTokenType === 'literal' && (match = this._langcode.exec(input)))\n type = 'langcode', value = match[1];\n // Try to find a keyword.\n else if (match = this._keyword.exec(input))\n type = match[0];\n break;\n\n case '.':\n // Try to find a dot as punctuation.\n if (input.length === 1 ? inputFinished : (input[1] < '0' || input[1] > '9')) {\n type = '.';\n matchLength = 1;\n break;\n }\n // Fall through to numerical case (could be a decimal dot).\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n case '+':\n case '-':\n // Try to find a number.\n if (match = this._number.exec(input)) {\n type = 'literal';\n value = '\"' + match[0] + '\"^^http://www.w3.org/2001/XMLSchema#' +\n (match[1] ? 'double' : (/^[+\\-]?\\d+$/.test(match[0]) ? 'integer' : 'decimal'));\n }\n break;\n\n case 'B':\n case 'b':\n case 'p':\n case 'P':\n case 'G':\n case 'g':\n // Try to find a SPARQL-style keyword.\n if (match = this._sparqlKeyword.exec(input))\n type = match[0].toUpperCase();\n else\n inconclusive = true;\n break;\n\n case 'f':\n case 't':\n // Try to match a boolean.\n if (match = this._boolean.exec(input))\n type = 'literal', value = '\"' + match[0] + '\"^^http://www.w3.org/2001/XMLSchema#boolean';\n else\n inconclusive = true;\n break;\n\n case 'a':\n // Try to find an abbreviated predicate.\n if (match = this._shortPredicates.exec(input))\n type = 'abbreviation', value = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';\n else\n inconclusive = true;\n break;\n\n case ',':\n case ';':\n case '[':\n case ']':\n case '(':\n case ')':\n case '{':\n case '}':\n // The next token is punctuation\n matchLength = 1;\n type = firstChar;\n break;\n\n default:\n inconclusive = true;\n }\n\n // Some first characters do not allow an immediate decision, so inspect more.\n if (inconclusive) {\n // Try to find a prefix.\n if ((this._prevTokenType === '@prefix' || this._prevTokenType === 'PREFIX') &&\n (match = this._prefix.exec(input)))\n type = 'prefix', value = match[1] || '';\n // Try to find a prefixed name. Since it can contain (but not end with) a dot,\n // we always need a non-dot character before deciding it is a prefixed name.\n // Therefore, try inserting a space if we're at the end of the input.\n else if ((match = this._prefixed.exec(input)) ||\n inputFinished && (match = this._prefixed.exec(input + ' ')))\n type = 'prefixed', prefix = match[1] || '', value = this._unescape(match[2]);\n }\n\n // A type token is special: it can only be emitted after an IRI or prefixed name is read.\n if (this._prevTokenType === '^')\n type = (type === 'IRI' || type === 'prefixed') ? 'type' : '';\n\n // What if nothing of the above was found?\n if (!type) {\n // We could be in streaming mode, and then we just wait for more input to arrive.\n // Otherwise, a syntax error has occurred in the input.\n // One exception: error on an unaccounted linebreak (= not inside a triple-quoted literal).\n if (inputFinished || (!/^'''|^\"\"\"/.test(input) && /\\n|\\r/.test(input)))\n return reportSyntaxError(this);\n else\n return this._input = input;\n }\n\n // Emit the parsed token.\n callback(null, { line: line, type: type, value: value, prefix: prefix });\n this._prevTokenType = type;\n\n // Advance to next part to tokenize.\n input = input.substr(matchLength || match[0].length, input.length);\n }\n\n // Signals the syntax error through the callback\n function reportSyntaxError(self) { callback(self._syntaxError(/^\\S*/.exec(input)[0])); }\n },\n\n // ### `_unescape` replaces N3 escape codes by their corresponding characters.\n _unescape: function (item) {\n try {\n return item.replace(escapeSequence, function (sequence, unicode4, unicode8, escapedChar) {\n var charCode;\n if (unicode4) {\n charCode = parseInt(unicode4, 16);\n if (isNaN(charCode)) throw new Error(); // can never happen (regex), but helps performance\n return fromCharCode(charCode);\n }\n else if (unicode8) {\n charCode = parseInt(unicode8, 16);\n if (isNaN(charCode)) throw new Error(); // can never happen (regex), but helps performance\n if (charCode <= 0xFFFF) return fromCharCode(charCode);\n return fromCharCode(0xD800 + ((charCode -= 0x10000) / 0x400), 0xDC00 + (charCode & 0x3FF));\n }\n else {\n var replacement = escapeReplacements[escapedChar];\n if (!replacement)\n throw new Error();\n return replacement;\n }\n });\n }\n catch (error) { return null; }\n },\n\n // ### `_syntaxError` creates a syntax error for the given issue\n _syntaxError: function (issue) {\n this._input = null;\n return new Error('Syntax error: unexpected \"' + issue + '\" on line ' + this._line + '.');\n },\n\n\n // ## Public methods\n\n // ### `tokenize` starts the transformation of an N3 document into an array of tokens.\n // The input can be a string or a stream.\n tokenize: function (input, callback) {\n var self = this;\n this._line = 1;\n\n // If the input is a string, continuously emit tokens through the callback until the end.\n if (typeof input === 'string') {\n this._input = input;\n immediately(function () { self._tokenizeToEnd(callback, true); });\n }\n // Otherwise, the input will be streamed.\n else {\n this._input = '';\n\n // If no input was given, it will be streamed through `addChunk` and ended with `end`\n if (!input || typeof input === 'function') {\n this.addChunk = addChunk;\n this.end = end;\n if (!callback)\n callback = input;\n }\n // Otherwise, the input itself must be a stream\n else {\n if (typeof input.setEncoding === 'function')\n input.setEncoding('utf8');\n input.on('data', addChunk);\n input.on('end', end);\n }\n }\n\n // Adds the data chunk to the buffer and parses as far as possible\n function addChunk(data) {\n if (self._input !== null) {\n self._input += data;\n self._tokenizeToEnd(callback, false);\n }\n }\n\n // Parses until the end\n function end() {\n if (self._input !== null)\n self._tokenizeToEnd(callback, true);\n }\n },\n};\n\n// ## Exports\n\n// Export the `N3Lexer` class as a whole.\nmodule.exports = N3Lexer;\n","// **N3Parser** parses N3 documents.\nvar N3Lexer = require('./N3Lexer');\n\nvar RDF_PREFIX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n RDF_NIL = RDF_PREFIX + 'nil',\n RDF_FIRST = RDF_PREFIX + 'first',\n RDF_REST = RDF_PREFIX + 'rest';\n\nvar absoluteIRI = /^[a-z][a-z0-9+.-]*:/i,\n schemeAuthority = /^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i,\n dotSegments = /(?:^|\\/)\\.\\.?(?:$|[\\/#?])/;\n\n// The next ID for new blank nodes\nvar blankNodePrefix = 0, blankNodeCount = 0;\n\n// ## Constructor\nfunction N3Parser(options) {\n if (!(this instanceof N3Parser))\n return new N3Parser(options);\n this._tripleStack = [];\n this._graph = null;\n\n // Set the document IRI.\n options = options || {};\n this._setBase(options.documentIRI);\n\n // Set supported features depending on the format.\n var format = (typeof options.format === 'string') && options.format.match(/\\w*$/)[0].toLowerCase(),\n isTurtle = format === 'turtle', isTriG = format === 'trig',\n isNTriples = /triple/.test(format), isNQuads = /quad/.test(format),\n isLineMode = isNTriples || isNQuads;\n if (!(this._supportsNamedGraphs = !isTurtle))\n this._readPredicateOrNamedGraph = this._readPredicate;\n this._supportsQuads = !(isTurtle || isTriG || isNTriples);\n // Disable relative IRIs in N-Triples or N-Quads mode\n if (isLineMode) {\n this._base = '';\n this._resolveIRI = function (token) {\n this._error('Disallowed relative IRI', token);\n return this._callback = noop, this._subject = null;\n };\n }\n this._blankNodePrefix = typeof options.blankNodePrefix !== 'string' ? '' :\n '_:' + options.blankNodePrefix.replace(/^_:/, '');\n this._lexer = options.lexer || new N3Lexer({ lineMode: isLineMode });\n}\n\n// ## Private class methods\n\n// ### `_resetBlankNodeIds` restarts blank node identification.\nN3Parser._resetBlankNodeIds = function () {\n blankNodePrefix = blankNodeCount = 0;\n};\n\nN3Parser.prototype = {\n // ## Private methods\n\n // ### `_setBase` sets the base IRI to resolve relative IRIs.\n _setBase: function (baseIRI) {\n if (!baseIRI)\n baseIRI = null;\n else if (baseIRI.indexOf('#') >= 0)\n throw new Error('Invalid base IRI ' + baseIRI);\n // Set base IRI and its components\n if (this._base = baseIRI) {\n this._basePath = baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(schemeAuthority);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n },\n\n // ### `_readInTopContext` reads a token when in the top context.\n _readInTopContext: function (token) {\n switch (token.type) {\n // If an EOF token arrives in the top context, signal that we're done.\n case 'eof':\n if (this._graph !== null)\n return this._error('Unclosed graph', token);\n delete this._prefixes._;\n return this._callback(null, null, this._prefixes);\n // It could be a prefix declaration.\n case '@prefix':\n this._sparqlStyle = false;\n return this._readPrefix;\n case 'PREFIX':\n this._sparqlStyle = true;\n return this._readPrefix;\n // It could be a base declaration.\n case '@base':\n this._sparqlStyle = false;\n return this._readBaseIRI;\n case 'BASE':\n this._sparqlStyle = true;\n return this._readBaseIRI;\n // It could be a graph.\n case '{':\n if (this._supportsNamedGraphs) {\n this._graph = '';\n this._subject = null;\n return this._readSubject;\n }\n case 'GRAPH':\n if (this._supportsNamedGraphs)\n return this._readNamedGraphLabel;\n // Otherwise, the next token must be a subject.\n default:\n return this._readSubject(token);\n }\n },\n\n // ### `_readSubject` reads a triple's subject.\n _readSubject: function (token) {\n this._predicate = null;\n switch (token.type) {\n case 'IRI':\n if (this._base === null || absoluteIRI.test(token.value))\n this._subject = token.value;\n else\n this._subject = this._resolveIRI(token);\n break;\n case 'prefixed':\n var prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error('Undefined prefix \"' + token.prefix + ':\"', token);\n this._subject = prefix + token.value;\n break;\n case '[':\n // Start a new triple with a new blank node as subject.\n this._subject = '_:b' + blankNodeCount++;\n this._tripleStack.push({ subject: this._subject, predicate: null, object: null, type: 'blank' });\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._tripleStack.push({ subject: RDF_NIL, predicate: null, object: null, type: 'list' });\n this._subject = null;\n return this._readListItem;\n case '}':\n return this._readPunctuation(token);\n default:\n return this._error('Expected subject but got ' + token.type, token);\n }\n // The next token must be a predicate,\n // or, if the subject was actually a graph IRI, a named graph.\n return this._readPredicateOrNamedGraph;\n },\n\n // ### `_readPredicate` reads a triple's predicate.\n _readPredicate: function (token) {\n var type = token.type;\n switch (type) {\n case 'IRI':\n case 'abbreviation':\n if (this._base === null || absoluteIRI.test(token.value))\n this._predicate = token.value;\n else\n this._predicate = this._resolveIRI(token);\n break;\n case 'prefixed':\n if (token.prefix === '_')\n return this._error('Disallowed blank node as predicate', token);\n var prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error('Undefined prefix \"' + token.prefix + ':\"', token);\n this._predicate = prefix + token.value;\n break;\n case '.':\n case ']':\n case '}':\n // Expected predicate didn't come, must have been trailing semicolon.\n if (this._predicate === null)\n return this._error('Unexpected ' + type, token);\n this._subject = null;\n return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token);\n case ';':\n // Extra semicolons can be safely ignored\n return this._readPredicate;\n default:\n return this._error('Expected predicate to follow \"' + this._subject + '\"', token);\n }\n // The next token must be an object.\n return this._readObject;\n },\n\n // ### `_readObject` reads a triple's object.\n _readObject: function (token) {\n switch (token.type) {\n case 'IRI':\n if (this._base === null || absoluteIRI.test(token.value))\n this._object = token.value;\n else\n this._object = this._resolveIRI(token);\n break;\n case 'prefixed':\n var prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error('Undefined prefix \"' + token.prefix + ':\"', token);\n this._object = prefix + token.value;\n break;\n case 'literal':\n this._object = token.value;\n return this._readDataTypeOrLang;\n case '[':\n // Start a new triple with a new blank node as subject.\n var blank = '_:b' + blankNodeCount++;\n this._tripleStack.push({ subject: this._subject, predicate: this._predicate, object: blank, type: 'blank' });\n this._subject = blank;\n return this._readBlankNodeHead;\n case '(':\n // Start a new list\n this._tripleStack.push({ subject: this._subject, predicate: this._predicate, object: RDF_NIL, type: 'list' });\n this._subject = null;\n return this._readListItem;\n default:\n return this._error('Expected object to follow \"' + this._predicate + '\"', token);\n }\n return this._getTripleEndReader();\n },\n\n // ### `_readPredicateOrNamedGraph` reads a triple's predicate, or a named graph.\n _readPredicateOrNamedGraph: function (token) {\n return token.type === '{' ? this._readGraph(token) : this._readPredicate(token);\n },\n\n // ### `_readGraph` reads a graph.\n _readGraph: function (token) {\n if (token.type !== '{')\n return this._error('Expected graph but got ' + token.type, token);\n // The \"subject\" we read is actually the GRAPH's label\n this._graph = this._subject, this._subject = null;\n return this._readSubject;\n },\n\n // ### `_readBlankNodeHead` reads the head of a blank node.\n _readBlankNodeHead: function (token) {\n if (token.type === ']') {\n this._subject = null;\n return this._readBlankNodeTail(token);\n }\n else {\n this._predicate = null;\n return this._readPredicate(token);\n }\n },\n\n // ### `_readBlankNodeTail` reads the end of a blank node.\n _readBlankNodeTail: function (token) {\n if (token.type !== ']')\n return this._readBlankNodePunctuation(token);\n\n // Store blank node triple.\n if (this._subject !== null)\n this._callback(null, { subject: this._subject,\n predicate: this._predicate,\n object: this._object,\n graph: this._graph || '' });\n\n // Restore parent triple that contains the blank node.\n var triple = this._tripleStack.pop();\n this._subject = triple.subject;\n // Was the blank node the object?\n if (triple.object !== null) {\n // Restore predicate and object as well, and continue by reading punctuation.\n this._predicate = triple.predicate;\n this._object = triple.object;\n return this._getTripleEndReader();\n }\n // The blank node was the subject, so continue reading the predicate.\n // If the blank node didn't contain any predicates, it could also be the label of a named graph.\n return this._predicate !== null ? this._readPredicate : this._readPredicateOrNamedGraph;\n },\n\n // ### `_readDataTypeOrLang` reads an _optional_ data type or language.\n _readDataTypeOrLang: function (token) {\n switch (token.type) {\n case 'type':\n var value;\n if (token.prefix === '') {\n if (this._base === null || absoluteIRI.test(token.value))\n value = token.value;\n else\n value = this._resolveIRI(token);\n }\n else {\n var prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error('Undefined prefix \"' + token.prefix + ':\"', token);\n value = prefix + token.value;\n }\n this._object += '^^' + value;\n return this._getTripleEndReader();\n case 'langcode':\n this._object += '@' + token.value.toLowerCase();\n return this._getTripleEndReader();\n default:\n return this._getTripleEndReader().call(this, token);\n }\n },\n\n // ### `_readListItem` reads items from a list.\n _readListItem: function (token) {\n var item = null, // The actual list item.\n itemHead = null, // The head of the rdf:first predicate.\n prevItemHead = this._subject, // The head of the previous rdf:first predicate.\n stack = this._tripleStack, // The stack of triples part of recursion (lists, blanks, etc.).\n parentTriple = stack[stack.length - 1], // The triple containing the current list.\n next = this._readListItem; // The next function to execute.\n\n switch (token.type) {\n case 'IRI':\n if (this._base === null || absoluteIRI.test(token.value))\n item = token.value;\n else\n item = this._resolveIRI(token);\n break;\n case 'prefixed':\n var prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error('Undefined prefix \"' + token.prefix + ':\"', token);\n item = prefix + token.value;\n break;\n case 'literal':\n item = token.value;\n next = this._readDataTypeOrLang;\n break;\n case '[':\n // Stack the current list triple and start a new triple with a blank node as subject.\n itemHead = '_:b' + blankNodeCount++;\n item = '_:b' + blankNodeCount++;\n stack.push({ subject: itemHead, predicate: RDF_FIRST, object: item, type: 'blank' });\n this._subject = item;\n next = this._readBlankNodeHead;\n break;\n case '(':\n // Stack the current list triple and start a new list\n itemHead = '_:b' + blankNodeCount++;\n stack.push({ subject: itemHead, predicate: RDF_FIRST, object: RDF_NIL, type: 'list' });\n this._subject = null;\n next = this._readListItem;\n break;\n case ')':\n // Restore the parent triple.\n stack.pop();\n // If this list is contained within a parent list, return the membership triple here.\n // This will be ` rdf:first .`.\n if (stack.length !== 0 && stack[stack.length - 1].type === 'list')\n this._callback(null, { subject: parentTriple.subject,\n predicate: parentTriple.predicate,\n object: parentTriple.object,\n graph: this._graph || '' });\n // Restore the parent triple's subject.\n this._subject = parentTriple.subject;\n // Was this list in the parent triple's subject?\n if (parentTriple.predicate === null) {\n // The next token is the predicate.\n next = this._readPredicate;\n // Skip writing the list tail if this was an empty list.\n if (parentTriple.subject === RDF_NIL)\n return next;\n }\n // The list was in the parent triple's object.\n else {\n // Restore the parent triple's predicate and object as well.\n this._predicate = parentTriple.predicate;\n this._object = parentTriple.object;\n next = this._getTripleEndReader();\n // Skip writing the list tail if this was an empty list.\n if (parentTriple.object === RDF_NIL)\n return next;\n }\n // Close the list by making the item head nil.\n itemHead = RDF_NIL;\n break;\n default:\n return this._error('Expected list item instead of \"' + token.type + '\"', token);\n }\n\n // Create a new blank node if no item head was assigned yet.\n if (itemHead === null)\n this._subject = itemHead = '_:b' + blankNodeCount++;\n\n // Is this the first element of the list?\n if (prevItemHead === null) {\n // This list is either the object or the subject.\n if (parentTriple.object === RDF_NIL)\n parentTriple.object = itemHead;\n else\n parentTriple.subject = itemHead;\n }\n else {\n // The rest of the list is in the current head.\n this._callback(null, { subject: prevItemHead,\n predicate: RDF_REST,\n object: itemHead,\n graph: this._graph || '' });\n }\n // Add the item's value.\n if (item !== null)\n this._callback(null, { subject: itemHead,\n predicate: RDF_FIRST,\n object: item,\n graph: this._graph || '' });\n return next;\n },\n\n // ### `_readPunctuation` reads punctuation between triples or triple parts.\n _readPunctuation: function (token) {\n var next, subject = this._subject, graph = this._graph;\n switch (token.type) {\n // A closing brace ends a graph\n case '}':\n if (this._graph === null)\n return this._error('Unexpected graph closing', token);\n this._graph = null;\n // A dot just ends the statement, without sharing anything with the next.\n case '.':\n this._subject = null;\n next = this._readInTopContext;\n break;\n // Semicolon means the subject is shared; predicate and object are different.\n case ';':\n next = this._readPredicate;\n break;\n // Comma means both the subject and predicate are shared; the object is different.\n case ',':\n next = this._readObject;\n break;\n // An IRI means this is a quad (only allowed if not already inside a graph).\n case 'IRI':\n if (this._supportsQuads && this._graph === null) {\n if (this._base === null || absoluteIRI.test(token.value))\n graph = token.value;\n else\n graph = this._resolveIRI(token);\n subject = this._subject;\n next = this._readQuadPunctuation;\n break;\n }\n // An prefixed name means this is a quad (only allowed if not already inside a graph).\n case 'prefixed':\n if (this._supportsQuads && this._graph === null) {\n var prefix = this._prefixes[token.prefix];\n if (prefix === undefined)\n return this._error('Undefined prefix \"' + token.prefix + ':\"', token);\n graph = prefix + token.value;\n next = this._readQuadPunctuation;\n break;\n }\n default:\n return this._error('Expected punctuation to follow \"' + this._object + '\"', token);\n }\n // A triple has been completed now, so return it.\n if (subject !== null)\n this._callback(null, { subject: subject,\n predicate: this._predicate,\n object: this._object,\n graph: graph || '' });\n return next;\n },\n\n // ### `_readBlankNodePunctuation` reads punctuation in a blank node\n _readBlankNodePunctuation: function (token) {\n var next;\n switch (token.type) {\n // Semicolon means the subject is shared; predicate and object are different.\n case ';':\n next = this._readPredicate;\n break;\n // Comma means both the subject and predicate are shared; the object is different.\n case ',':\n next = this._readObject;\n break;\n default:\n return this._error('Expected punctuation to follow \"' + this._object + '\"', token);\n }\n // A triple has been completed now, so return it.\n this._callback(null, { subject: this._subject,\n predicate: this._predicate,\n object: this._object,\n graph: this._graph || '' });\n return next;\n },\n\n // ### `_readQuadPunctuation` reads punctuation after a quad.\n _readQuadPunctuation: function (token) {\n if (token.type !== '.')\n return this._error('Expected dot to follow quad', token);\n return this._readInTopContext;\n },\n\n // ### `_readPrefix` reads the prefix of a prefix declaration.\n _readPrefix: function (token) {\n if (token.type !== 'prefix')\n return this._error('Expected prefix to follow @prefix', token);\n this._prefix = token.value;\n return this._readPrefixIRI;\n },\n\n // ### `_readPrefixIRI` reads the IRI of a prefix declaration.\n _readPrefixIRI: function (token) {\n if (token.type !== 'IRI')\n return this._error('Expected IRI to follow prefix \"' + this._prefix + ':\"', token);\n var prefixIRI;\n if (this._base === null || absoluteIRI.test(token.value))\n prefixIRI = token.value;\n else\n prefixIRI = this._resolveIRI(token);\n this._prefixes[this._prefix] = prefixIRI;\n this._prefixCallback(this._prefix, prefixIRI);\n return this._readDeclarationPunctuation;\n },\n\n // ### `_readBaseIRI` reads the IRI of a base declaration.\n _readBaseIRI: function (token) {\n if (token.type !== 'IRI')\n return this._error('Expected IRI to follow base declaration', token);\n try {\n this._setBase(this._base === null ||\n absoluteIRI.test(token.value) ? token.value : this._resolveIRI(token));\n }\n catch (error) { this._error(error.message, token); }\n return this._readDeclarationPunctuation;\n },\n\n // ### `_readNamedGraphLabel` reads the label of a named graph.\n _readNamedGraphLabel: function (token) {\n switch (token.type) {\n case 'IRI':\n case 'prefixed':\n return this._readSubject(token), this._readGraph;\n case '[':\n return this._readNamedGraphBlankLabel;\n default:\n return this._error('Invalid graph label', token);\n }\n },\n\n // ### `_readNamedGraphLabel` reads a blank node label of a named graph.\n _readNamedGraphBlankLabel: function (token) {\n if (token.type !== ']')\n return this._error('Invalid graph label', token);\n this._subject = '_:b' + blankNodeCount++;\n return this._readGraph;\n },\n\n // ### `_readDeclarationPunctuation` reads the punctuation of a declaration.\n _readDeclarationPunctuation: function (token) {\n // SPARQL-style declarations don't have punctuation.\n if (this._sparqlStyle)\n return this._readInTopContext(token);\n\n if (token.type !== '.')\n return this._error('Expected declaration to end with a dot', token);\n return this._readInTopContext;\n },\n\n // ### `_getTripleEndReader` gets the next reader function at the end of a triple.\n _getTripleEndReader: function () {\n var stack = this._tripleStack;\n if (stack.length === 0)\n return this._readPunctuation;\n\n switch (stack[stack.length - 1].type) {\n case 'blank':\n return this._readBlankNodeTail;\n case 'list':\n return this._readListItem;\n }\n },\n\n // ### `_error` emits an error message through the callback.\n _error: function (message, token) {\n this._callback(new Error(message + ' at line ' + token.line + '.'));\n },\n\n // ### `_resolveIRI` resolves a relative IRI token against the base path,\n // assuming that a base path has been set and that the IRI is indeed relative.\n _resolveIRI: function (token) {\n var iri = token.value;\n switch (iri[0]) {\n // An empty relative IRI indicates the base IRI\n case undefined: return this._base;\n // Resolve relative fragment IRIs against the base IRI\n case '#': return this._base + iri;\n // Resolve relative query string IRIs by replacing the query string\n case '?': return this._base.replace(/(?:\\?.*)?$/, iri);\n // Resolve root-relative IRIs at the root of the base IRI\n case '/':\n // Resolve scheme-relative IRIs to the scheme\n return (iri[1] === '/' ? this._baseScheme : this._baseRoot) + this._removeDotSegments(iri);\n // Resolve all other IRIs at the base IRI's path\n default:\n return this._removeDotSegments(this._basePath + iri);\n }\n },\n\n // ### `_removeDotSegments` resolves './' and '../' path segments in an IRI as per RFC3986.\n _removeDotSegments: function (iri) {\n // Don't modify the IRI if it does not contain any dot segments\n if (!dotSegments.test(iri))\n return iri;\n\n // Start with an imaginary slash before the IRI in order to resolve trailing './' and '../'\n var result = '', length = iri.length, i = -1, pathStart = -1, segmentStart = 0, next = '/';\n\n while (i < length) {\n switch (next) {\n // The path starts with the first slash after the authority\n case ':':\n if (pathStart < 0) {\n // Skip two slashes before the authority\n if (iri[++i] === '/' && iri[++i] === '/')\n // Skip to slash after the authority\n while ((pathStart = i + 1) < length && iri[pathStart] !== '/')\n i = pathStart;\n }\n break;\n // Don't modify a query string or fragment\n case '?':\n case '#':\n i = length;\n break;\n // Handle '/.' or '/..' path segments\n case '/':\n if (iri[i + 1] === '.') {\n next = iri[++i + 1];\n switch (next) {\n // Remove a '/.' segment\n case '/':\n result += iri.substring(segmentStart, i - 1);\n segmentStart = i + 1;\n break;\n // Remove a trailing '/.' segment\n case undefined:\n case '?':\n case '#':\n return result + iri.substring(segmentStart, i) + iri.substr(i + 1);\n // Remove a '/..' segment\n case '.':\n next = iri[++i + 1];\n if (next === undefined || next === '/' || next === '?' || next === '#') {\n result += iri.substring(segmentStart, i - 2);\n // Try to remove the parent path from result\n if ((segmentStart = result.lastIndexOf('/')) >= pathStart)\n result = result.substr(0, segmentStart);\n // Remove a trailing '/..' segment\n if (next !== '/')\n return result + '/' + iri.substr(i + 1);\n segmentStart = i + 1;\n }\n }\n }\n }\n next = iri[++i];\n }\n return result + iri.substring(segmentStart);\n },\n\n // ## Public methods\n\n // ### `parse` parses the N3 input and emits each parsed triple through the callback.\n parse: function (input, tripleCallback, prefixCallback) {\n // The read callback is the next function to be executed when a token arrives.\n // We start reading in the top context.\n this._readCallback = this._readInTopContext;\n this._prefixes = Object.create(null);\n this._prefixes._ = this._blankNodePrefix || '_:b' + blankNodePrefix++ + '_';\n\n // If the input argument is not given, shift parameters\n if (typeof input === 'function')\n prefixCallback = tripleCallback, tripleCallback = input, input = null;\n\n // Set the triple and prefix callbacks.\n this._callback = tripleCallback || noop;\n this._prefixCallback = prefixCallback || noop;\n\n // Execute the read callback when a token arrives.\n var self = this;\n this._lexer.tokenize(input, function (error, token) {\n if (error !== null)\n self._callback(error), self._callback = noop;\n else if (self._readCallback !== undefined)\n self._readCallback = self._readCallback(token);\n });\n\n // If no input was given, it can be added with `addChunk` and ended with `end`\n if (!input) {\n this.addChunk = this._lexer.addChunk;\n this.end = this._lexer.end;\n }\n },\n};\n\n// The empty function\nfunction noop() {}\n\n// ## Exports\n\n// Export the `N3Parser` class as a whole.\nmodule.exports = N3Parser;\n","// **N3Util** provides N3 utility functions\n\nvar Xsd = 'http://www.w3.org/2001/XMLSchema#';\nvar XsdString = Xsd + 'string';\nvar XsdInteger = Xsd + 'integer';\nvar XsdDecimal = Xsd + 'decimal';\nvar XsdBoolean = Xsd + 'boolean';\nvar RdfLangString = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString';\n\nvar N3Util = {\n // Tests whether the given entity (triple object) represents an IRI in the N3 library\n isIRI: function (entity) {\n if (!entity)\n return entity;\n var firstChar = entity[0];\n return firstChar !== '\"' && firstChar !== '_';\n },\n\n // Tests whether the given entity (triple object) represents a literal in the N3 library\n isLiteral: function (entity) {\n return entity && entity[0] === '\"';\n },\n\n // Tests whether the given entity (triple object) represents a blank node in the N3 library\n isBlank: function (entity) {\n return entity && entity.substr(0, 2) === '_:';\n },\n\n // Gets the string value of a literal in the N3 library\n getLiteralValue: function (literal) {\n var match = /^\"([^]*)\"/.exec(literal);\n if (!match)\n throw new Error(literal + ' is not a literal');\n return match[1];\n },\n\n // Gets the type of a literal in the N3 library\n getLiteralType: function (literal) {\n var match = /^\"[^]*\"(?:\\^\\^([^\"]+)|(@)[^@\"]+)?$/.exec(literal);\n if (!match)\n throw new Error(literal + ' is not a literal');\n return match[1] || (match[2] ? RdfLangString : XsdString);\n },\n\n // Gets the language of a literal in the N3 library\n getLiteralLanguage: function (literal) {\n var match = /^\"[^]*\"(?:@([^@\"]+)|\\^\\^[^\"]+)?$/.exec(literal);\n if (!match)\n throw new Error(literal + ' is not a literal');\n return match[1] ? match[1].toLowerCase() : '';\n },\n\n // Tests whether the given entity (triple object) represents a prefixed name\n isPrefixedName: function (entity) {\n return entity && /^[^:\\/\"']*:[^:\\/\"']+$/.test(entity);\n },\n\n // Expands the prefixed name to a full IRI (also when it occurs as a literal's type)\n expandPrefixedName: function (prefixedName, prefixes) {\n var match = /(?:^|\"\\^\\^)([^:\\/#\"'\\^_]*):[^\\/]*$/.exec(prefixedName), prefix, base, index;\n if (match)\n prefix = match[1], base = prefixes[prefix], index = match.index;\n if (base === undefined)\n return prefixedName;\n\n // The match index is non-zero when expanding a literal's type.\n return index === 0 ? base + prefixedName.substr(prefix.length + 1)\n : prefixedName.substr(0, index + 3) +\n base + prefixedName.substr(index + prefix.length + 4);\n },\n\n // Creates an IRI in N3.js representation\n createIRI: function (iri) {\n return iri && iri[0] === '\"' ? N3Util.getLiteralValue(iri) : iri;\n },\n\n // Creates a literal in N3.js representation\n createLiteral: function (value, modifier) {\n if (!modifier) {\n switch (typeof value) {\n case 'boolean':\n modifier = XsdBoolean;\n break;\n case 'number':\n if (isFinite(value)) {\n modifier = value % 1 === 0 ? XsdInteger : XsdDecimal;\n break;\n }\n default:\n return '\"' + value + '\"';\n }\n }\n return '\"' + value +\n (/^[a-z]+(-[a-z0-9]+)*$/i.test(modifier) ? '\"@' + modifier.toLowerCase()\n : '\"^^' + modifier);\n },\n};\n\n// Add the N3Util functions to the given object or its prototype\nfunction addN3Util(parent, toPrototype) {\n for (var name in N3Util)\n if (!toPrototype)\n parent[name] = N3Util[name];\n else\n parent.prototype[name] = applyToThis(N3Util[name]);\n\n return parent;\n}\n\n// Returns a function that applies `f` to the `this` object\nfunction applyToThis(f) {\n return function (a) { return f(this, a); };\n}\n\n// Expose N3Util, attaching all functions to it\nmodule.exports = addN3Util(addN3Util);\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n","exports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\n","// **N3Writer** writes N3 documents.\n\n// Matches a literal as represented in memory by the N3 library\nvar N3LiteralMatcher = /^\"([^]*)\"(?:\\^\\^(.+)|@([\\-a-z]+))?$/i;\n\n// rdf:type predicate (for 'a' abbreviation)\nvar RDF_PREFIX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n RDF_TYPE = RDF_PREFIX + 'type';\n\n// Characters in literals that require escaping\nvar escape = /[\"\\\\\\t\\n\\r\\b\\f\\u0000-\\u0019\\ud800-\\udbff]/,\n escapeAll = /[\"\\\\\\t\\n\\r\\b\\f\\u0000-\\u0019]|[\\ud800-\\udbff][\\udc00-\\udfff]/g,\n escapeReplacements = { '\\\\': '\\\\\\\\', '\"': '\\\\\"', '\\t': '\\\\t',\n '\\n': '\\\\n', '\\r': '\\\\r', '\\b': '\\\\b', '\\f': '\\\\f' };\n\n// ## Constructor\nfunction N3Writer(outputStream, options) {\n if (!(this instanceof N3Writer))\n return new N3Writer(outputStream, options);\n\n // Shift arguments if the first argument is not a stream\n if (outputStream && typeof outputStream.write !== 'function')\n options = outputStream, outputStream = null;\n options = options || {};\n\n // If no output stream given, send the output as string through the end callback\n if (!outputStream) {\n var output = '';\n this._outputStream = {\n write: function (chunk, encoding, done) { output += chunk; done && done(); },\n end: function (done) { done && done(null, output); },\n };\n this._endStream = true;\n }\n else {\n this._outputStream = outputStream;\n this._endStream = options.end === undefined ? true : !!options.end;\n }\n\n // Initialize writer, depending on the format\n this._subject = null;\n if (!(/triple|quad/i).test(options.format)) {\n this._graph = '';\n this._prefixIRIs = Object.create(null);\n options.prefixes && this.addPrefixes(options.prefixes);\n }\n else {\n this._writeTriple = this._writeTripleLine;\n }\n}\n\nN3Writer.prototype = {\n // ## Private methods\n\n // ### `_write` writes the argument to the output stream\n _write: function (string, callback) {\n this._outputStream.write(string, 'utf8', callback);\n },\n\n // ### `_writeTriple` writes the triple to the output stream\n _writeTriple: function (subject, predicate, object, graph, done) {\n try {\n // Write the graph's label if it has changed\n if (this._graph !== graph) {\n // Close the previous graph and start the new one\n this._write((this._subject === null ? '' : (this._graph ? '\\n}\\n' : '.\\n')) +\n (graph ? this._encodeIriOrBlankNode(graph) + ' {\\n' : ''));\n this._subject = null;\n // Don't treat identical blank nodes as repeating graphs\n this._graph = graph[0] !== '[' ? graph : ']';\n }\n // Don't repeat the subject if it's the same\n if (this._subject === subject) {\n // Don't repeat the predicate if it's the same\n if (this._predicate === predicate)\n this._write(', ' + this._encodeObject(object), done);\n // Same subject, different predicate\n else\n this._write(';\\n ' +\n this._encodePredicate(this._predicate = predicate) + ' ' +\n this._encodeObject(object), done);\n }\n // Different subject; write the whole triple\n else\n this._write((this._subject === null ? '' : '.\\n') +\n this._encodeSubject(this._subject = subject) + ' ' +\n this._encodePredicate(this._predicate = predicate) + ' ' +\n this._encodeObject(object), done);\n }\n catch (error) { done && done(error); }\n },\n\n // ### `_writeTripleLine` writes the triple or quad to the output stream as a single line\n _writeTripleLine: function (subject, predicate, object, graph, done) {\n // Don't use prefixes\n delete this._prefixMatch;\n // Write the triple\n try {\n this._write(this._encodeIriOrBlankNode(subject) + ' ' +\n this._encodeIriOrBlankNode(predicate) + ' ' +\n this._encodeObject(object) +\n (graph ? ' ' + this._encodeIriOrBlankNode(graph) + '.\\n' : '.\\n'), done);\n }\n catch (error) { done && done(error); }\n },\n\n // ### `_encodeIriOrBlankNode` represents an IRI or blank node\n _encodeIriOrBlankNode: function (entity) {\n // A blank node or list is represented as-is\n var firstChar = entity[0];\n if (firstChar === '[' || firstChar === '(' || firstChar === '_' && entity[1] === ':')\n return entity;\n // Escape special characters\n if (escape.test(entity))\n entity = entity.replace(escapeAll, characterReplacer);\n // Try to represent the IRI as prefixed name\n var prefixMatch = this._prefixRegex.exec(entity);\n return !prefixMatch ? '<' + entity + '>' :\n (!prefixMatch[1] ? entity : this._prefixIRIs[prefixMatch[1]] + prefixMatch[2]);\n },\n\n // ### `_encodeLiteral` represents a literal\n _encodeLiteral: function (value, type, language) {\n // Escape special characters\n if (escape.test(value))\n value = value.replace(escapeAll, characterReplacer);\n // Write the literal, possibly with type or language\n if (language)\n return '\"' + value + '\"@' + language;\n else if (type)\n return '\"' + value + '\"^^' + this._encodeIriOrBlankNode(type);\n else\n return '\"' + value + '\"';\n },\n\n // ### `_encodeSubject` represents a subject\n _encodeSubject: function (subject) {\n if (subject[0] === '\"')\n throw new Error('A literal as subject is not allowed: ' + subject);\n // Don't treat identical blank nodes as repeating subjects\n if (subject[0] === '[')\n this._subject = ']';\n return this._encodeIriOrBlankNode(subject);\n },\n\n // ### `_encodePredicate` represents a predicate\n _encodePredicate: function (predicate) {\n if (predicate[0] === '\"')\n throw new Error('A literal as predicate is not allowed: ' + predicate);\n return predicate === RDF_TYPE ? 'a' : this._encodeIriOrBlankNode(predicate);\n },\n\n // ### `_encodeObject` represents an object\n _encodeObject: function (object) {\n // Represent an IRI or blank node\n if (object[0] !== '\"')\n return this._encodeIriOrBlankNode(object);\n // Represent a literal\n var match = N3LiteralMatcher.exec(object);\n if (!match) throw new Error('Invalid literal: ' + object);\n return this._encodeLiteral(match[1], match[2], match[3]);\n },\n\n // ### `_blockedWrite` replaces `_write` after the writer has been closed\n _blockedWrite: function () {\n throw new Error('Cannot write because the writer has been closed.');\n },\n\n // ### `addTriple` adds the triple to the output stream\n addTriple: function (subject, predicate, object, graph, done) {\n // The triple was given as a triple object, so shift parameters\n if (object === undefined)\n this._writeTriple(subject.subject, subject.predicate, subject.object,\n subject.graph || '', predicate);\n // The optional `graph` parameter was not provided\n else if (typeof graph !== 'string')\n this._writeTriple(subject, predicate, object, '', graph);\n // The `graph` parameter was provided\n else\n this._writeTriple(subject, predicate, object, graph, done);\n },\n\n // ### `addTriples` adds the triples to the output stream\n addTriples: function (triples) {\n for (var i = 0; i < triples.length; i++)\n this.addTriple(triples[i]);\n },\n\n // ### `addPrefix` adds the prefix to the output stream\n addPrefix: function (prefix, iri, done) {\n var prefixes = {};\n prefixes[prefix] = iri;\n this.addPrefixes(prefixes, done);\n },\n\n // ### `addPrefixes` adds the prefixes to the output stream\n addPrefixes: function (prefixes, done) {\n // Add all useful prefixes\n var prefixIRIs = this._prefixIRIs, hasPrefixes = false;\n for (var prefix in prefixes) {\n // Verify whether the prefix can be used and does not exist yet\n var iri = prefixes[prefix];\n if (/[#\\/]$/.test(iri) && prefixIRIs[iri] !== (prefix += ':')) {\n hasPrefixes = true;\n prefixIRIs[iri] = prefix;\n // Finish a possible pending triple\n if (this._subject !== null) {\n this._write(this._graph ? '\\n}\\n' : '.\\n');\n this._subject = null, this._graph = '';\n }\n // Write prefix\n this._write('@prefix ' + prefix + ' <' + iri + '>.\\n');\n }\n }\n // Recreate the prefix matcher\n if (hasPrefixes) {\n var IRIlist = '', prefixList = '';\n for (var prefixIRI in prefixIRIs) {\n IRIlist += IRIlist ? '|' + prefixIRI : prefixIRI;\n prefixList += (prefixList ? '|' : '') + prefixIRIs[prefixIRI];\n }\n IRIlist = IRIlist.replace(/[\\]\\/\\(\\)\\*\\+\\?\\.\\\\\\$]/g, '\\\\$&');\n this._prefixRegex = new RegExp('^(?:' + prefixList + ')[^\\/]*$|' +\n '^(' + IRIlist + ')([a-zA-Z][\\\\-_a-zA-Z0-9]*)$');\n }\n // End a prefix block with a newline\n this._write(hasPrefixes ? '\\n' : '', done);\n },\n\n // ### `blank` creates a blank node with the given content\n blank: function (predicate, object) {\n var children = predicate, child, length;\n // Empty blank node\n if (predicate === undefined)\n children = [];\n // Blank node passed as blank(\"predicate\", \"object\")\n else if (typeof predicate === 'string')\n children = [{ predicate: predicate, object: object }];\n // Blank node passed as blank({ predicate: predicate, object: object })\n else if (!('length' in predicate))\n children = [predicate];\n\n switch (length = children.length) {\n // Generate an empty blank node\n case 0:\n return '[]';\n // Generate a non-nested one-triple blank node\n case 1:\n child = children[0];\n if (child.object[0] !== '[')\n return '[ ' + this._encodePredicate(child.predicate) + ' ' +\n this._encodeObject(child.object) + ' ]';\n // Generate a multi-triple or nested blank node\n default:\n var contents = '[';\n // Write all triples in order\n for (var i = 0; i < length; i++) {\n child = children[i];\n // Write only the object is the predicate is the same as the previous\n if (child.predicate === predicate)\n contents += ', ' + this._encodeObject(child.object);\n // Otherwise, write the predicate and the object\n else {\n contents += (i ? ';\\n ' : '\\n ') +\n this._encodePredicate(child.predicate) + ' ' +\n this._encodeObject(child.object);\n predicate = child.predicate;\n }\n }\n return contents + '\\n]';\n }\n },\n\n // ### `list` creates a list node with the given content\n list: function (elements) {\n var length = elements && elements.length || 0, contents = new Array(length);\n for (var i = 0; i < length; i++)\n contents[i] = this._encodeObject(elements[i]);\n return '(' + contents.join(' ') + ')';\n },\n\n // ### `_prefixRegex` matches a prefixed name or IRI that begins with one of the added prefixes\n _prefixRegex: /$0^/,\n\n // ### `end` signals the end of the output stream\n end: function (done) {\n // Finish a possible pending triple\n if (this._subject !== null) {\n this._write(this._graph ? '\\n}\\n' : '.\\n');\n this._subject = null;\n }\n // Disallow further writing\n this._write = this._blockedWrite;\n\n // Try to end the underlying stream, ensuring done is called exactly one time\n var singleDone = done && function (error, result) { singleDone = null, done(error, result); };\n if (this._endStream) {\n try { return this._outputStream.end(singleDone); }\n catch (error) { /* error closing stream */ }\n }\n singleDone && singleDone();\n },\n};\n\n// Replaces a character by its escaped version\nfunction characterReplacer(character) {\n // Replace a single character by its escaped version\n var result = escapeReplacements[character];\n if (result === undefined) {\n // Replace a single character with its 4-bit unicode escape sequence\n if (character.length === 1) {\n result = character.charCodeAt(0).toString(16);\n result = '\\\\u0000'.substr(0, 6 - result.length) + result;\n }\n // Replace a surrogate pair with its 8-bit unicode escape sequence\n else {\n result = ((character.charCodeAt(0) - 0xD800) * 0x400 +\n character.charCodeAt(1) + 0x2400).toString(16);\n result = '\\\\U00000000'.substr(0, 10 - result.length) + result;\n }\n }\n return result;\n}\n\n// ## Exports\n\n// Export the `N3Writer` class as a whole.\nmodule.exports = N3Writer;\n","/* global $SolidTestEnvironment */\n/**\n *\n * Project: rdflib.js\n *\n * @file: fetcher.js\n *\n * Description: contains functions for requesting/fetching/retracting\n * This implements quite a lot of the web architecture.\n * A fetcher is bound to a specific quad store, into which\n * it loads stuff and into which it writes its metadata\n * @@ The metadata could be optionally a separate graph\n *\n * - implements semantics of HTTP headers, Internet Content Types\n * - selects parsers for rdf/xml, n3, rdfa, grddl\n *\n * TO do:\n * - Implement a runtime registry for parsers and serializers\n * -\n */\n\n/**\n * Things to test: callbacks on request, refresh, retract\n * loading from HTTP, HTTPS, FTP, FILE, others?\n * To do:\n * Firing up a mail client for mid: (message:) URLs\n */\nconst IndexedFormula = require('./indexed-formula')\nconst log = require('./log')\nconst N3Parser = require('./n3parser')\nconst NamedNode = require('./named-node')\nconst Namespace = require('./namespace')\nconst rdfParse = require('./parse')\nconst parseRDFaDOM = require('./rdfaparser').parseRDFaDOM\nconst RDFParser = require('./rdfxmlparser')\nconst Uri = require('./uri')\nconst Util = require('./util')\nconst serialize = require('./serialize')\n\n// This is a special fetch withich does OIDC auth, catching 401 errors\nconst auth = require('solid-auth-client')\nconst fetch = auth ? auth.fetch : (a, b) => window.fetch(a, b)\n\nconst Parsable = {\n 'text/n3': true,\n 'text/turtle': true,\n 'application/rdf+xml': true,\n 'application/xhtml+xml': true,\n 'text/html': true,\n 'application/ld+json': true\n}\n\n// This is a minimal set to allow the use of damaged servers if necessary\nconst CONTENT_TYPE_BY_EXT = {\n 'rdf': 'application/rdf+xml',\n 'owl': 'application/rdf+xml',\n 'n3': 'text/n3',\n 'ttl': 'text/turtle',\n 'nt': 'text/n3',\n 'acl': 'text/n3',\n 'html': 'text/html',\n 'xml': 'text/xml'\n}\n\n// Convenience namespaces needed in this module.\n// These are deliberately not exported as the user application should\n// make its own list and not rely on the prefixes used here,\n// and not be tempted to add to them, and them clash with those of another\n// application.\nconst ns = {\n link: Namespace('http://www.w3.org/2007/ont/link#'),\n http: Namespace('http://www.w3.org/2007/ont/http#'),\n httph: Namespace('http://www.w3.org/2007/ont/httph#'), // headers\n rdf: Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#'),\n rdfs: Namespace('http://www.w3.org/2000/01/rdf-schema#'),\n dc: Namespace('http://purl.org/dc/elements/1.1/'),\n ldp: Namespace('http://www.w3.org/ns/ldp#')\n}\n\nclass Handler {\n constructor (response, dom) {\n this.response = response\n this.dom = dom\n }\n}\n\nclass RDFXMLHandler extends Handler {\n static toString () {\n return 'RDFXMLHandler'\n }\n\n static register (fetcher) {\n fetcher.mediatypes['application/rdf+xml'] = {\n 'q': 0.9\n }\n }\n\n parse (fetcher, responseText, options, response) {\n let kb = fetcher.store\n if (!this.dom) {\n this.dom = Util.parseXML(responseText)\n }\n let root = this.dom.documentElement\n if (root.nodeName === 'parsererror') { // Mozilla only See issue/issue110\n // have to fail the request\n return fetcher.failFetch(options, 'Badly formed XML in ' +\n options.resource.uri, 'parse_error')\n }\n let parser = new RDFParser(kb)\n try {\n parser.parse(this.dom, options.original.uri, options.original, response)\n } catch (err) {\n return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err,\n 'parse_error')\n }\n if (!options.noMeta) {\n kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode)\n }\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nRDFXMLHandler.pattern = new RegExp('application/rdf\\\\+xml')\n\nclass XHTMLHandler extends Handler {\n static toString () {\n return 'XHTMLHandler'\n }\n\n static register (fetcher) {\n fetcher.mediatypes['application/xhtml+xml'] = {}\n }\n\n parse (fetcher, responseText, options, response) {\n let relation, reverse\n if (!this.dom) {\n this.dom = Util.parseXML(responseText)\n }\n let kb = fetcher.store\n\n // dc:title\n let title = this.dom.getElementsByTagName('title')\n if (title.length > 0) {\n kb.add(options.resource, ns.dc('title'), kb.literal(title[0].textContent),\n options.resource)\n // log.info(\"Inferring title of \" + xhr.resource)\n }\n\n // link rel\n let links = this.dom.getElementsByTagName('link')\n for (let x = links.length - 1; x >= 0; x--) { // @@ rev\n relation = links[x].getAttribute('rel')\n reverse = false\n if (!relation) {\n relation = links[x].getAttribute('rev')\n reverse = true\n }\n if (relation) {\n fetcher.linkData(options.original, relation,\n links[x].getAttribute('href'), options.resource, reverse)\n }\n }\n\n // Data Islands\n let scripts = this.dom.getElementsByTagName('script')\n for (let i = 0; i < scripts.length; i++) {\n let contentType = scripts[i].getAttribute('type')\n if (Parsable[contentType]) {\n rdfParse(scripts[i].textContent, kb, options.original.uri, contentType)\n rdfParse(scripts[i].textContent, kb, options.original.uri, contentType)\n }\n }\n\n if (!options.noMeta) {\n kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode)\n }\n\n if (!options.noRDFa && parseRDFaDOM) { // enable by default\n try {\n parseRDFaDOM(this.dom, kb, options.original.uri)\n } catch (err) {\n let msg = 'Error trying to parse ' + options.resource + ' as RDFa:\\n' +\n err + ':\\n' + err.stack\n return fetcher.failFetch(options, msg, 'parse_error')\n }\n }\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nXHTMLHandler.pattern = new RegExp('application/xhtml')\n\nclass XMLHandler extends Handler {\n static toString () {\n return 'XMLHandler'\n }\n\n static register (fetcher) {\n fetcher.mediatypes['text/xml'] = { 'q': 0.5 }\n fetcher.mediatypes['application/xml'] = { 'q': 0.5 }\n }\n\n parse (fetcher, responseText, options, response) {\n let dom = Util.parseXML(responseText)\n\n // XML Semantics defined by root element namespace\n // figure out the root element\n for (let c = 0; c < dom.childNodes.length; c++) {\n // is this node an element?\n if (dom.childNodes[c].nodeType === 1) {\n // We've found the first element, it's the root\n let ns = dom.childNodes[c].namespaceURI\n\n // Is it RDF/XML?\n if (ns && ns === ns['rdf']) {\n fetcher.addStatus(options.req,\n 'Has XML root element in the RDF namespace, so assume RDF/XML.')\n\n let rdfHandler = new RDFXMLHandler(this.response, dom)\n return rdfHandler.parse(fetcher, responseText, options, response)\n }\n\n break\n }\n }\n\n // Or it could be XHTML?\n // Maybe it has an XHTML DOCTYPE?\n if (dom.doctype) {\n // log.info(\"We found a DOCTYPE in \" + xhr.resource)\n if (dom.doctype.name === 'html' &&\n dom.doctype.publicId.match(/^-\\/\\/W3C\\/\\/DTD XHTML/) &&\n dom.doctype.systemId.match(/http:\\/\\/www.w3.org\\/TR\\/xhtml/)) {\n fetcher.addStatus(options.req,\n 'Has XHTML DOCTYPE. Switching to XHTML Handler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response, dom)\n return xhtmlHandler.parse(fetcher, responseText, options, response)\n }\n }\n\n // Or what about an XHTML namespace?\n let html = dom.getElementsByTagName('html')[0]\n if (html) {\n let xmlns = html.getAttribute('xmlns')\n if (xmlns && xmlns.match(/^http:\\/\\/www.w3.org\\/1999\\/xhtml/)) {\n fetcher.addStatus(options.req,\n 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response, dom)\n return xhtmlHandler.parse(fetcher, responseText, options, response)\n }\n }\n\n // At this point we should check the namespace document (cache it!) and\n // look for a GRDDL transform\n // @@ Get namespace document , parse it, look for grddl:namespaceTransform ?y\n // Apply ?y to dom\n // We give up. What dialect is this?\n return fetcher.failFetch(options,\n 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\\n' +\n responseText.slice(0, 80), 901)\n }\n}\nXMLHandler.pattern = new RegExp('(text|application)/(.*)xml')\n\nclass HTMLHandler extends Handler {\n static toString () {\n return 'HTMLHandler'\n }\n\n static register (fetcher) {\n fetcher.mediatypes['text/html'] = {\n 'q': 0.9\n }\n }\n\n parse (fetcher, responseText, options, response) {\n let kb = fetcher.store\n\n // We only handle XHTML so we have to figure out if this is XML\n // log.info(\"Sniffing HTML \" + xhr.resource + \" for XHTML.\")\n\n if (responseText.match(/\\s*<\\?xml\\s+version\\s*=[^<>]+\\?>/)) {\n fetcher.addStatus(options.req, \"Has an XML declaration. We'll assume \" +\n \"it's XHTML as the content-type was text/html.\\n\")\n\n let xhtmlHandler = new XHTMLHandler(this.response)\n return xhtmlHandler.parse(fetcher, responseText, options, response)\n }\n\n // DOCTYPE\n // There is probably a smarter way to do this\n if (responseText.match(/.*/)) {\n fetcher.addStatus(options.req,\n 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response)\n return xhtmlHandler.parse(fetcher, responseText, options, response)\n }\n\n // xmlns\n if (responseText.match(/[^(/)) {\n fetcher.addStatus(options.req,\n 'Has default namespace for XHTML, so switching to XHTMLHandler.\\n')\n\n let xhtmlHandler = new XHTMLHandler(this.response)\n return xhtmlHandler.parse(fetcher, responseText, options, response)\n }\n\n // dc:title\n // no need to escape '/' here\n let titleMatch = (new RegExp('([\\\\s\\\\S]+?)', 'im')).exec(responseText)\n if (titleMatch) {\n kb.add(options.resource, ns.dc('title'), kb.literal(titleMatch[1]),\n options.resource) // think about xml:lang later\n }\n kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode)\n fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.')\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nHTMLHandler.pattern = new RegExp('text/html')\n\nclass TextHandler extends Handler {\n static toString () {\n return 'TextHandler'\n }\n\n static register (fetcher) {\n fetcher.mediatypes['text/plain'] = {\n 'q': 0.5\n }\n }\n\n parse (fetcher, responseText, options, response) {\n // We only speak dialects of XML right now. Is this XML?\n\n // Look for an XML declaration\n if (responseText.match(/\\s*<\\?xml\\s+version\\s*=[^<>]+\\?>/)) {\n fetcher.addStatus(options.req, 'Warning: ' + options.resource +\n \" has an XML declaration. We'll assume \" +\n \"it's XML but its content-type wasn't XML.\\n\")\n\n let xmlHandler = new XMLHandler(this.response)\n return xmlHandler.parse(fetcher, responseText, options, response)\n }\n\n // Look for an XML declaration\n if (responseText.slice(0, 500).match(/xmlns:/)) {\n fetcher.addStatus(options.req, \"May have an XML namespace. We'll assume \" +\n \"it's XML but its content-type wasn't XML.\\n\")\n\n let xmlHandler = new XMLHandler(this.response)\n return xmlHandler.parse(fetcher, responseText, options, response)\n }\n\n // We give up finding semantics - this is not an error, just no data\n fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.')\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nTextHandler.pattern = new RegExp('text/plain')\n\nclass N3Handler extends Handler {\n static toString () {\n return 'N3Handler'\n }\n\n static register (fetcher) {\n fetcher.mediatypes['text/n3'] = {\n 'q': '1.0'\n } // as per 2008 spec\n /*\n fetcher.mediatypes['application/x-turtle'] = {\n 'q': 1.0\n } // pre 2008\n */\n fetcher.mediatypes['text/turtle'] = {\n 'q': 1.0\n } // post 2008\n }\n\n parse (fetcher, responseText, options, response) {\n // Parse the text of this non-XML file\n let kb = fetcher.store\n // console.log('web.js: Parsing as N3 ' + xhr.resource.uri + ' base: ' +\n // xhr.original.uri) // @@@@ comment me out\n // fetcher.addStatus(xhr.req, \"N3 not parsed yet...\")\n let p = N3Parser(kb, kb, options.original.uri, options.original.uri,\n null, null, '', null)\n // p.loadBuf(xhr.responseText)\n try {\n p.loadBuf(responseText)\n } catch (err) {\n let msg = 'Error trying to parse ' + options.resource +\n ' as Notation3:\\n' + err + ':\\n' + err.stack\n // dump(msg+\"\\n\")\n return fetcher.failFetch(options, msg, 'parse_error', response)\n }\n\n fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.')\n fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode)\n // var args = [xhr.original.uri] // Other args needed ever?\n\n return fetcher.doneFetch(options, this.response)\n }\n}\nN3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\\\+)?(n3|turtle)')\n\nconst HANDLERS = {\n RDFXMLHandler, XHTMLHandler, XMLHandler, HTMLHandler, TextHandler, N3Handler\n}\n\n/** Fetcher\n *\n * The Fetcher object is a helper object for a quadstore\n * which turns it from an offline store to an online store.\n * The fetcher deals with loading data files rom the web,\n * figuring how to parse them. It will also refresh, remove, the data\n * and put back the fata to the web.\n */\nclass Fetcher {\n /**\n * @constructor\n */\n constructor (store, options = {}) {\n this.store = store || new IndexedFormula()\n this.timeout = options.timeout || 30000\n\n this._fetch = options.fetch || fetch\n\n if (!this._fetch) {\n throw new Error('No _fetch function availble for Fetcher')\n }\n\n this.appNode = this.store.bnode() // Denoting this session\n this.store.fetcher = this // Bi-linked\n this.requested = {}\n // this.requested[uri] states:\n // undefined no record of web access or records reset\n // true has been requested, fetch in progress\n // 'done' received, Ok\n // 401 Not logged in\n // 403 HTTP status unauthorized\n // 404 Resource does not exist. Can be created etc.\n // 'redirected' In attempt to counter CORS problems retried.\n // 'parse_error' Parse error\n // 'unsupported_protocol' URI is not a protocol Fetcher can deal with\n // other strings mean various other errors.\n //\n this.timeouts = {} // list of timeouts associated with a requested URL\n this.redirectedTo = {} // When 'redirected'\n this.fetchQueue = {}\n this.fetchCallbacks = {} // fetchCallbacks[uri].push(callback)\n\n this.nonexistent = {} // keep track of explicit 404s -> we can overwrite etc\n this.lookedUp = {}\n this.handlers = []\n this.mediatypes = {\n 'image/*': { 'q': 0.9 },\n '*/*': { 'q': 0.1 } // Must allow access to random content\n }\n\n // Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail',\n // 'refresh', 'retract', 'done'])\n // In switching to fetch(), 'recv', 'headers' and 'load' do not make sense\n Util.callbackify(this, ['request', 'fail', 'refresh', 'retract', 'done'])\n\n Object.keys(HANDLERS).map(key => this.addHandler(HANDLERS[key]))\n }\n\n static crossSiteProxy (uri) {\n if (Fetcher.crossSiteProxyTemplate) {\n return Fetcher.crossSiteProxyTemplate\n .replace('{uri}', encodeURIComponent(uri))\n } else {\n return undefined\n }\n }\n\n /**\n * @param uri {string}\n *\n * @returns {string}\n */\n static offlineOverride (uri) {\n // Map the URI to a localhost proxy if we are running on localhost\n // This is used for working offline, e.g. on planes.\n // Is the script itself is running in localhost, then access all\n // data in a localhost mirror.\n // Do not remove without checking with TimBL\n let requestedURI = uri\n\n var UI\n if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) &&\n UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) {\n if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') {\n requestedURI = 'http://localhost/' + requestedURI.slice(7)\n log.warn('Localhost kludge for offline use: actually getting <' +\n requestedURI + '>')\n } else {\n // log.warn(\"Localhost kludge NOT USED <\" + requestedURI + \">\")\n }\n } else {\n // log.warn(\"Localhost kludge OFF offline use: actually getting <\" +\n // requestedURI + \">\")\n }\n\n return requestedURI\n }\n\n static proxyIfNecessary (uri) {\n var UI\n if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.isExtension) {\n return uri\n } // Extension does not need proxy\n\n if (typeof $SolidTestEnvironment !== 'undefined' &&\n $SolidTestEnvironment.localSiteMap) {\n // nested dictionaries of URI parts from origin down\n let hostpath = uri.split('/').slice(2) // the bit after the //\n\n const lookup = (parts, index) => {\n let z = index[parts.shift()]\n\n if (!z) { return null }\n\n if (typeof z === 'string') {\n return z + parts.join('/')\n }\n\n if (!parts) { return null }\n\n return lookup(parts, z)\n }\n\n const y = lookup(hostpath, $SolidTestEnvironment.localSiteMap)\n\n if (y) {\n return y\n }\n }\n\n // browser does 2014 on as https browser script not trusted\n // If the web app origin is https: then the mixed content rules\n // prevent it loading insecure http: stuff so we need proxy.\n if (Fetcher.crossSiteProxyTemplate &&\n typeof document !== 'undefined' && document.location &&\n ('' + document.location).slice(0, 6) === 'https:' && // origin is secure\n uri.slice(0, 5) === 'http:') { // requested data is not\n return Fetcher.crossSiteProxyTemplate\n .replace('{uri}', encodeURIComponent(uri))\n }\n\n return uri\n }\n\n /**\n * Tests whether the uri's protocol is supported by the Fetcher.\n *\n * @param uri {string}\n *\n * @returns {boolean}\n */\n static unsupportedProtocol (uri) {\n let pcol = Uri.protocol(uri)\n\n return (pcol === 'tel' || pcol === 'mailto' || pcol === 'urn')\n }\n\n /**\n * @param requestedURI {string}\n * @param options {Object}\n *\n * @returns {boolean}\n */\n static withCredentials (requestedURI, options = {}) {\n // 2014 problem:\n // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card.\n // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin'\n // header when the credentials flag is true.\n // @ Many ontology files under http: and need CORS wildcard ->\n // can't have withCredentials\n\n // @@ Kludge -- need for webid which typically is served from https\n let withCredentials = requestedURI.startsWith('https:')\n\n if (options.withCredentials !== undefined) {\n withCredentials = options.withCredentials\n }\n\n return withCredentials\n }\n\n /**\n * Promise-based load function\n *\n * Loads a web resource or resources into the store.\n *\n * A resource may be given as NamedNode object, or as a plain URI.\n * an arrsy of resources will be given, in which they will be fetched in parallel.\n * By default, the HTTP headers are recorded also, in the same store, in a separate graph.\n * This allows code like editable() for example to test things about the resource.\n *\n * @param uri {Array|Array|NamedNode|string}\n *\n * @param [options={}] {Object}\n *\n * @param [options.fetch] {Function}\n *\n * @param [options.referringTerm] {NamedNode} Referring term, the resource which\n * referred to this (for tracking bad links)\n *\n * @param [options.contentType] {string} Provided content type (for writes)\n *\n * @param [options.forceContentType] {string} Override the incoming header to\n * force the data to be treated as this content-type (for reads)\n *\n * @param [options.force] {boolean} Load the data even if loaded before.\n * Also sets the `Cache-Control:` header to `no-cache`\n *\n * @param [options.baseURI=docuri] {Node|string} Original uri to preserve\n * through proxying etc (`xhr.original`).\n *\n * @param [options.proxyUsed] {boolean} Whether this request is a retry via\n * a proxy (generally done from an error handler)\n *\n * @param [options.withCredentials] {boolean} flag for XHR/CORS etc\n *\n * @param [options.clearPreviousData] {boolean} Before we parse new data,\n * clear old, but only on status 200 responses\n *\n * @param [options.noMeta] {boolean} Prevents the addition of various metadata\n * triples (about the fetch request) to the store\n *\n * @param [options.noRDFa] {boolean}\n *\n * @returns {Promise}\n */\n load (uri, options = {}) {\n if (uri instanceof Array) {\n return Promise.all(\n uri.map(x => { return this.load(x, Object.assign({}, options)) })\n )\n }\n\n let docuri = uri.uri || uri\n docuri = docuri.split('#')[0]\n\n options = this.initFetchOptions(docuri, options)\n\n return this.pendingFetchPromise(docuri, options.baseURI, options)\n }\n\n /**\n * @param uri {string}\n * @param originalUri {string}\n * @param options {Object}\n * @returns {Promise}\n */\n pendingFetchPromise (uri, originalUri, options) {\n let pendingPromise\n\n // Check to see if some request is already dealing with this uri\n if (!options.force && this.fetchQueue[originalUri]) {\n pendingPromise = this.fetchQueue[originalUri]\n } else {\n pendingPromise = Promise\n .race([\n this.setRequestTimeout(uri, options),\n this.fetchUri(uri, options)\n ])\n this.fetchQueue[originalUri] = pendingPromise\n\n // Clean up the queued promise after a time, if it's resolved\n this.cleanupFetchRequest(originalUri, options, this.timeout)\n }\n\n return pendingPromise.then(x => {\n if (uri in this.timeouts) {\n this.timeouts[uri].forEach(clearTimeout)\n delete this.timeouts[uri]\n }\n return x\n })\n }\n\n cleanupFetchRequest (originalUri, options, timeout) {\n this.timeouts[originalUri] = (this.timeouts[originalUri] || []).concat(setTimeout(() => {\n if (!this.isPending(originalUri)) {\n delete this.fetchQueue[originalUri]\n }\n }, timeout))\n }\n\n /**\n * @param uri {string}\n * @param options {Object}\n *\n * @returns {Object}\n */\n initFetchOptions (uri, options) {\n let kb = this.store\n\n let isGet = !options.method || options.method.toUpperCase() === 'GET'\n if (!isGet) {\n options.force = true\n }\n\n options.resource = kb.sym(uri) // This might be proxified\n options.baseURI = options.baseURI || uri // Preserve though proxying etc\n options.original = kb.sym(options.baseURI)\n options.req = kb.bnode()\n options.headers = options.headers || {}\n\n if (options.contentType) {\n options.headers['content-type'] = options.contentType\n }\n\n if (options.force) {\n options.cache = 'no-cache'\n }\n\n let acceptString = this.acceptString()\n options.headers['accept'] = acceptString\n\n let requestedURI = Fetcher.offlineOverride(uri)\n options.requestedURI = requestedURI\n\n if (Fetcher.withCredentials(requestedURI, options)) {\n options.credentials = 'include'\n }\n\n let actualProxyURI = Fetcher.proxyIfNecessary(requestedURI)\n if (requestedURI !== actualProxyURI) {\n options.proxyUsed = true\n }\n options.actualProxyURI = actualProxyURI\n\n return options\n }\n\n /**\n * (The promise chain ends in either a `failFetch()` or a `doneFetch()`)\n *\n * @param docuri {string}\n * @param options {Object}\n *\n * @returns {Promise} fetch() result or an { error, status } object\n */\n fetchUri (docuri, options) {\n if (!docuri) {\n return Promise.reject(new Error('Cannot fetch an empty uri'))\n }\n\n if (Fetcher.unsupportedProtocol(docuri)) {\n return this.failFetch(options, 'fetcher: Unsupported protocol', 'unsupported_protocol')\n }\n\n let state = this.getState(docuri)\n\n if (!options.force) {\n if (state === 'fetched') { // URI already fetched and added to store\n return Promise.resolve(\n this.doneFetch(options, {status: 200, ok: true, statusText: 'Already loaded into quadstore.'})\n )\n }\n if (state === 'failed' && this.requested[docuri] === 404) { // Remember nonexistence\n let message = 'Previously failed: ' + this.requested[docuri]\n let dummyResponse = {\n url: docuri,\n status: this.requested[docuri],\n statusText: message,\n responseText: message,\n headers: {}, // Headers() ???\n ok: false,\n body: null,\n bodyUsed: false,\n size: 0,\n timeout: 0\n }\n return this.failFetch(options, message,\n this.requested[docuri], dummyResponse)\n }\n } else {\n // options.force == true\n delete this.nonexistent[docuri]\n }\n\n this.fireCallbacks('request', [docuri])\n\n this.requested[docuri] = true // mark this uri as 'requested'\n\n if (!options.noMeta) {\n this.saveRequestMetadata(docuri, options)\n }\n\n let { actualProxyURI } = options\n\n return this._fetch(actualProxyURI, options)\n .then(response => this.handleResponse(response, docuri, options),\n error => {\n let dummyResponse = {\n url: actualProxyURI,\n status: 999, // @@ what number/string should fetch failures report?\n statusText: (error.name || 'network failure') + ': ' +\n (error.errno || error.code || error.type),\n responseText: error.message,\n headers: {}, // Headers() ???\n ok: false,\n body: null,\n bodyUsed: false,\n size: 0,\n timeout: 0\n }\n console.log('Fetcher: <' + actualProxyURI + '> Non-HTTP fetch error: ' + error)\n return this.failFetch(options, 'fetch failed: ' + error, 999, dummyResponse) // Fake status code: fetch exception\n\n // handleError expects a response so we fake some important bits.\n /*\n this.handleError(, docuri, options)\n */\n }\n )\n }\n\n /**\n * Asks for a doc to be loaded if necessary then calls back\n *\n * Calling methods:\n * nowOrWhenFetched (uri, userCallback)\n * nowOrWhenFetched (uri, options, userCallback)\n * nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old\n * nowOrWhenFetched (uri, referringTerm, userCallback) <-- old\n *\n * Options include:\n * referringTerm The document in which this link was found.\n * this is valuable when finding the source of bad URIs\n * force boolean. Never mind whether you have tried before,\n * load this from scratch.\n * forceContentType Override the incoming header to force the data to be\n * treated as this content-type.\n *\n * Callback function takes:\n *\n * ok True if the fetch worked, and got a 200 response.\n * False if any error happened\n *\n * errmessage Text error message if not OK.\n *\n * response The fetch Response object (was: XHR) if there was was one\n * includes response.status as the HTTP status if any.\n */\n nowOrWhenFetched (uri, p2, userCallback, options = {}) {\n uri = uri.uri || uri // allow symbol object or string to be passed\n\n if (typeof p2 === 'function') {\n // nowOrWhenFetched (uri, userCallback)\n userCallback = p2\n } else if (typeof p2 === 'undefined') { // original calling signature\n // referringTerm = undefined\n } else if (p2 instanceof NamedNode) {\n // referringTerm = p2\n options.referringTerm = p2\n } else {\n // nowOrWhenFetched (uri, options, userCallback)\n options = p2\n }\n\n this.load(uri, options)\n .then(fetchResponse => {\n if (userCallback) {\n if (fetchResponse) {\n if (fetchResponse.ok) {\n userCallback(true, 'OK', fetchResponse)\n } else {\n console.log('@@@ fetcher.js Should not take this path !!!!!!!!!!!!')\n let oops = 'HTTP error: Status ' + fetchResponse.status + ' (' + fetchResponse.statusText + ')'\n if (fetchResponse.responseText) {\n oops += ' ' + fetchResponse.responseText // not in 404, dns error, nock failure\n }\n console.log(oops + ' fetching ' + uri)\n userCallback(false, oops, fetchResponse)\n }\n } else {\n let oops = ('@@ nowOrWhenFetched: no response object!')\n console.log(oops)\n userCallback(false, oops)\n }\n }\n }, function (err) {\n var message = err.message || err.statusText\n message = 'Failed to load <' + uri + '> ' + message\n console.log(message)\n if (err.response && err.response.status) {\n message += ' status: ' + err.response.status\n }\n userCallback(false, message, err.response)\n })\n }\n\n /**\n * Records a status message (as a literal node) by appending it to the\n * request's metadata status collection.\n *\n * @param req {BlankNode}\n * @param statusMessage {string}\n */\n addStatus (req, statusMessage) {\n // \n let now = new Date()\n statusMessage = '[' + now.getHours() + ':' + now.getMinutes() + ':' +\n now.getSeconds() + '.' + now.getMilliseconds() + '] ' + statusMessage\n // \n let kb = this.store\n\n let statusNode = kb.the(req, ns.link('status'))\n if (statusNode && statusNode.append) {\n statusNode.append(kb.literal(statusMessage))\n } else {\n log.warn('web.js: No list to add to: ' + statusNode + ',' + statusMessage)\n }\n }\n\n /**\n * Records errors in the system on failure:\n *\n * - Adds an entry to the request status collection\n * - Adds an error triple with the fail message to the metadata\n * - Fires the 'fail' callback\n * - Rejects with an error result object, which has a response object if any\n *\n * @param options {Object}\n * @param errorMessage {string}\n * @param statusCode {number}\n * @param response {Response} // when an fetch() error\n *\n * @returns {Promise}\n */\n failFetch (options, errorMessage, statusCode, response) {\n this.addStatus(options.req, errorMessage)\n\n if (!options.noMeta) {\n this.store.add(options.original, ns.link('error'), errorMessage)\n }\n\n let meth = (options.method || 'GET').toUpperCase()\n let isGet = meth === 'GET' || meth === 'HEAD'\n\n if (isGet) { // only cache the status code on GET or HEAD\n if (!options.resource.sameTerm(options.original)) {\n console.log('@@ Recording failure ' + meth + ' original ' + options.original +\n '( as ' + options.resource + ') : ' + statusCode)\n } else {\n console.log('@@ Recording ' + meth + ' failure for ' + options.original + ': ' + statusCode)\n }\n this.requested[Uri.docpart(options.original.uri)] = statusCode\n this.fireCallbacks('fail', [options.original.uri, errorMessage])\n }\n\n var err = new Error('Fetcher: ' + errorMessage)\n\n // err.ok = false // Is taken as a response, will work too @@ phase out?\n err.status = statusCode\n err.statusText = errorMessage\n err.response = response\n\n return Promise.reject(err)\n }\n\n // in the why part of the quad distinguish between HTML and HTTP header\n // Reverse is set iif the link was rev= as opposed to rel=\n linkData (originalUri, rel, uri, why, reverse) {\n if (!uri) return\n let kb = this.store\n let predicate\n // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10\n let obj = kb.sym(Uri.join(uri, originalUri.uri))\n\n if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' ||\n rel === 'describedby') {\n if (obj.uri === originalUri.uri) { return }\n predicate = ns.rdfs('seeAlso')\n } else if (rel === 'type') {\n predicate = kb.sym('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')\n } else {\n // See https://www.iana.org/assignments/link-relations/link-relations.xml\n // Alas not yet in RDF yet for each predicate\n // encode space in e.g. rel=\"shortcut icon\"\n predicate = kb.sym(\n Uri.join(encodeURIComponent(rel),\n 'http://www.iana.org/assignments/link-relations/')\n )\n }\n if (reverse) {\n kb.add(obj, predicate, originalUri, why)\n } else {\n kb.add(originalUri, predicate, obj, why)\n }\n }\n\n parseLinkHeader (linkHeader, originalUri, reqNode) {\n if (!linkHeader) { return }\n\n // const linkexp = /<[^>]*>\\s*(\\s*;\\s*[^()<>@,;:\"/[\\]?={} \\t]+=(([^()<>@,;:\"/[]?={} \\t]+)|(\"[^\"]*\")))*(,|$)/g\n // const paramexp = /[^()<>@,;:\"/[]?={} \\t]+=(([^()<>@,;:\"/[]?={} \\t]+)|(\"[^\"]*\"))/g\n\n // From https://www.dcode.fr/regular-expression-simplificator:\n // const linkexp = /<[^>]*>\\s*(\\s*;\\s*[^()<>@,;:\"/[\\]?={} t]+=[\"]))*[,$]/g\n // const paramexp = /[^\\\\<>@,;:\"\\/\\[\\]?={} \\t]+=[\"])/g\n // Original:\n const linkexp = /<[^>]*>\\s*(\\s*;\\s*[^()<>@,;:\"/[\\]?={} \\t]+=(([^\\(\\)<>@,;:\"\\/\\[\\]\\?={} \\t]+)|(\"[^\"]*\")))*(,|$)/g\n const paramexp = /[^\\(\\)<>@,;:\"\\/\\[\\]\\?={} \\t]+=(([^\\(\\)<>@,;:\"\\/\\[\\]\\?={} \\t]+)|(\"[^\"]*\"))/g\n\n const matches = linkHeader.match(linkexp)\n\n for (let i = 0; i < matches.length; i++) {\n let split = matches[i].split('>')\n let href = split[0].substring(1)\n let ps = split[1]\n let s = ps.match(paramexp)\n for (let j = 0; j < s.length; j++) {\n let p = s[j]\n let paramsplit = p.split('=')\n // var name = paramsplit[0]\n let rel = paramsplit[1].replace(/[\"']/g, '') // '\"\n this.linkData(originalUri, rel, href, reqNode)\n }\n }\n }\n\n doneFetch (options, response) {\n this.addStatus(options.req, 'Done.')\n this.requested[options.original.uri] = 'done'\n\n this.fireCallbacks('done', [options.original.uri])\n\n response.req = options.req // Set the request meta blank node\n\n return response\n }\n\n /**\n * Note two nodes are now smushed\n * If only one was flagged as looked up, then the new node is looked up again,\n * which will make sure all the URIs are dereferenced\n */\n nowKnownAs (was, now) {\n if (this.lookedUp[was.uri]) {\n // Transfer userCallback\n if (!this.lookedUp[now.uri]) {\n this.lookUpThing(now, was)\n }\n } else if (this.lookedUp[now.uri]) {\n if (!this.lookedUp[was.uri]) {\n this.lookUpThing(was, now)\n }\n }\n }\n\n /**\n * Writes back to the web what we have in the store for this uri\n *\n * @param uri {Node|string}\n * @param [options={}]\n *\n * @returns {Promise}\n */\n putBack (uri, options = {}) {\n uri = uri.uri || uri // Accept object or string\n let doc = new NamedNode(uri).doc() // strip off #\n options.contentType = options.contentType || 'text/turtle'\n options.data = serialize(doc, this.store, doc.uri, options.contentType)\n return this.webOperation('PUT', uri, options)\n }\n\n webCopy (here, there, contentType) {\n return this.webOperation('GET', here)\n .then((result) => {\n return this.webOperation(\n 'PUT', // change to binary from text\n there, { data: result.responseText, contentType })\n })\n }\n\n /**\n * @param uri {string}\n * @param [options] {Object}\n *\n * @returns {Promise}\n */\n delete (uri, options) {\n return this.webOperation('DELETE', uri, options)\n .then(response => {\n this.requested[uri] = 404\n this.nonexistent[uri] = true\n this.unload(this.store.sym(uri))\n\n return response\n })\n }\n\n /**\n * @param parentURI {string} URI of parent container\n * @param [folderName] {string} Optional folder name (slug)\n * @param [data] {string} Optional folder metadata\n *\n * @returns {Promise}\n */\n createContainer (parentURI, folderName, data) {\n let headers = {\n // Force the right mime type for containers\n 'content-type': 'text/turtle',\n 'link': ns.ldp('BasicContainer') + '; rel=\"type\"'\n }\n\n if (folderName) {\n headers['slug'] = folderName\n }\n\n let options = { headers }\n\n if (data) {\n options.body = data\n }\n\n return this.webOperation('POST', parentURI, options)\n }\n\n /**\n * A generic web opeation, at the fetch() level.\n * does not invole the quadstore.\n *\n * Returns promise of Response\n * If data is returned, copies it to response.responseText before returning\n *\n * @param method\n * @param uri or NamedNode\n * @param options\n *\n * @returns {Promise}\n */\n webOperation (method, uri, options = {}) {\n uri = uri.uri || uri // Allow a NamedNode to be passed as it is very common\n options.method = method\n options.body = options.data || options.body\n options.force = true\n const fetcher = this\n\n if (options.body && !options.contentType) {\n throw new Error('Web operation sending data must have a defined contentType.')\n }\n if (options.contentType) {\n options.headers = options.headers || {}\n options.headers['content-type'] = options.contentType\n }\n if (Fetcher.withCredentials(uri, options)) {\n options.credentials = 'include' // Otherwise coookies are not sent\n }\n\n return new Promise(function (resolve, reject) {\n fetcher._fetch(uri, options).then(response => {\n if (response.ok) {\n if (response.body) {\n response.text().then(data => {\n response.responseText = data\n resolve(response)\n })\n } else {\n resolve(response)\n }\n } else {\n let msg = 'Web error: ' + response.status\n if (response.statusText) msg += ' (' + response.statusText + ')'\n msg += ' on ' + method + ' of <' + uri + '>'\n if (response.responseText) msg += ': ' + response.responseText\n let e2 = new Error(msg)\n e2.response = response\n reject(e2)\n }\n }, err => {\n let msg = 'Fetch error for ' + method + ' of <' + uri + '>:' + err\n reject(new Error(msg))\n })\n })\n }\n\n /**\n * Looks up something.\n * Looks up all the URIs a things has.\n *\n * @param term {NamedNode} canonical term for the thing whose URI is\n * to be dereferenced\n * @param rterm {NamedNode} the resource which referred to this\n * (for tracking bad links)\n *\n * @returns {Promise}\n */\n lookUpThing (term, rterm) {\n let uris = this.store.uris(term) // Get all URIs\n uris = uris.map(u => Uri.docpart(u)) // Drop hash fragments\n\n uris.forEach(u => {\n this.lookedUp[u] = true\n })\n\n return this.load(uris, { referringTerm: rterm })\n }\n\n /**\n * Looks up response header.\n *\n * @param doc\n * @param header\n *\n * @returns {Array|undefined} a list of header values found in a stored HTTP\n * response, or [] if response was found but no header found,\n * or undefined if no response is available.\n * Looks for { [] link:requestedURI ?uri; link:response [ httph:header-name ?value ] }\n */\n getHeader (doc, header) {\n const kb = this.store\n const requests = kb.each(undefined, ns.link('requestedURI'), doc.uri)\n\n for (let r = 0; r < requests.length; r++) {\n let request = requests[r]\n if (request !== undefined) {\n let response = kb.any(request, ns.link('response'))\n\n if (response !== undefined) {\n console.log('@@@ looking for ' + ns.httph(header.toLowerCase()))\n let results = kb.each(response, ns.httph(header.toLowerCase()))\n\n if (results.length) {\n return results.map(v => { return v.value })\n }\n\n return []\n }\n }\n }\n return undefined\n }\n\n /**\n *\n * @param docuri\n * @param options\n */\n saveRequestMetadata (docuri, options) {\n let req = options.req\n let kb = this.store\n let rterm = options.referringTerm\n\n this.addStatus(options.req, 'Accept: ' + options.headers['accept'])\n\n if (rterm && rterm.uri) {\n kb.add(docuri, ns.link('requestedBy'), rterm.uri, this.appNode)\n }\n\n if (options.original && options.original.uri !== docuri) {\n kb.add(req, ns.link('orginalURI'), kb.literal(options.original.uri),\n this.appNode)\n }\n\n const now = new Date()\n const timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' +\n now.getSeconds() + '] '\n\n kb.add(req, ns.rdfs('label'),\n kb.literal(timeNow + ' Request for ' + docuri), this.appNode)\n kb.add(req, ns.link('requestedURI'), kb.literal(docuri), this.appNode)\n kb.add(req, ns.link('status'), kb.collection(), this.appNode)\n }\n\n saveResponseMetadata (response, options) {\n const kb = this.store\n\n let responseNode = kb.bnode()\n\n kb.add(options.req, ns.link('response'), responseNode, responseNode)\n kb.add(responseNode, ns.http('status'),\n kb.literal(response.status), responseNode)\n kb.add(responseNode, ns.http('statusText'),\n kb.literal(response.statusText), responseNode)\n\n if (!options.resource.uri.startsWith('http')) {\n return responseNode\n }\n\n // Save the response headers\n response.headers.forEach((value, header) => {\n kb.add(responseNode, ns.httph(header), value, responseNode)\n\n if (header === 'content-type') {\n kb.add(options.resource, ns.rdf('type'), Util.mediaTypeClass(value), responseNode)\n }\n })\n\n return responseNode\n }\n\n objectRefresh (term) {\n let uris = this.store.uris(term) // Get all URIs\n if (typeof uris !== 'undefined') {\n for (let i = 0; i < uris.length; i++) {\n this.refresh(this.store.sym(Uri.docpart(uris[i])))\n // what about rterm?\n }\n }\n }\n\n /* refresh Reload data from a given document\n **\n ** @param {NamedNode} term - An RDF Named Node for the eodcument in question\n ** @param {function } userCallback - A function userCallback(ok, message, response)\n */\n refresh (term, userCallback) { // sources_refresh\n this.fireCallbacks('refresh', arguments)\n\n this.nowOrWhenFetched(term, { force: true, clearPreviousData: true },\n userCallback)\n }\n\n /* refreshIfExpired Conditional refresh if Expired\n **\n ** @param {NamedNode} term - An RDF Named Node for the eodcument in question\n ** @param {function } userCallback - A function userCallback(ok, message, response)\n */\n refreshIfExpired (term, userCallback) {\n let exp = this.getHeader(term, 'Expires')\n if (!exp || (new Date(exp).getTime()) <= (new Date().getTime())) {\n this.refresh(term, userCallback)\n } else {\n userCallback(true, 'Not expired', {})\n }\n }\n\n retract (term) { // sources_retract\n this.store.removeMany(undefined, undefined, undefined, term)\n if (term.uri) {\n delete this.requested[Uri.docpart(term.uri)]\n }\n this.fireCallbacks('retract', arguments)\n }\n\n getState (docuri) {\n if (typeof this.requested[docuri] === 'undefined') {\n return 'unrequested'\n } else if (this.requested[docuri] === true) {\n return 'requested'\n } else if (this.requested[docuri] === 'done') {\n return 'fetched'\n } else if (this.requested[docuri] === 'redirected') {\n return this.getState(this.redirectedTo[docuri])\n } else { // An non-200 HTTP error status\n return 'failed'\n }\n }\n\n isPending (docuri) { // sources_pending\n // doing anyStatementMatching is wasting time\n // if it's not pending: false -> flailed\n // 'done' -> done 'redirected' -> redirected\n return this.requested[docuri] === true\n }\n\n unload (term) {\n this.store.removeDocument(term)\n delete this.requested[term.uri] // So it can be loaded again\n }\n\n addHandler (handler) {\n this.handlers.push(handler)\n handler.register(this)\n }\n\n retryNoCredentials (docuri, options) {\n console.log('web: Retrying with no credentials for ' + options.resource)\n\n options.retriedWithNoCredentials = true // protect against being called twice\n\n delete this.requested[docuri] // forget the original request happened\n\n let newOptions = Object.assign({}, options, { withCredentials: false })\n\n this.addStatus(options.req,\n 'Abort: Will retry with credentials SUPPRESSED to see if that helps')\n\n return this.load(docuri, newOptions)\n }\n\n /**\n * Tests whether a request is being made to a cross-site URI (for purposes\n * of retrying with a proxy)\n *\n * @param uri {string}\n *\n * @returns {boolean}\n */\n isCrossSite (uri) {\n // Mashup situation, not node etc\n if (typeof document === 'undefined' || !document.location) {\n return false\n }\n\n const hostpart = Uri.hostpart\n const here = '' + document.location\n return hostpart(here) && hostpart(uri) && hostpart(here) !== hostpart(uri)\n }\n\n /**\n * Called when there's a network error in fetch(), or a response\n * with status of 0.\n *\n * @param response {Response|Error}\n * @param docuri {string}\n * @param options {Object}\n *\n * @returns {Promise}\n */\n handleError (response, docuri, options) {\n if (this.isCrossSite(docuri)) {\n // Make sure we haven't retried already\n if (options.withCredentials && !options.retriedWithNoCredentials) {\n return this.retryNoCredentials(docuri, options)\n }\n\n // Now attempt retry via proxy\n let proxyUri = Fetcher.crossSiteProxy(docuri)\n\n if (proxyUri && !options.proxyUsed) {\n console.log('web: Direct failed so trying proxy ' + proxyUri)\n\n return this.redirectToProxy(proxyUri, options)\n }\n }\n\n var message\n if (response.message) {\n message = 'Fetch error: ' + response.message\n } else {\n message = response.statusText\n if (response.responseText) {\n message += ` ${response.responseText}`\n }\n }\n\n // This is either not a CORS error, or retries have been made\n return this.failFetch(options, message, response.status || 998, response)\n }\n\n // deduce some things from the HTTP transaction\n addType (rdfType, req, kb, locURI) { // add type to all redirected resources too\n let prev = req\n if (locURI) {\n var reqURI = kb.any(prev, ns.link('requestedURI'))\n if (reqURI && reqURI !== locURI) {\n kb.add(kb.sym(locURI), ns.rdf('type'), rdfType, this.appNode)\n }\n }\n for (;;) {\n const doc = kb.any(prev, ns.link('requestedURI'))\n if (doc && doc.value) {\n kb.add(kb.sym(doc.value), ns.rdf('type'), rdfType, this.appNode)\n } // convert Literal\n prev = kb.any(undefined, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), prev)\n if (!prev) { break }\n var response = kb.any(prev, kb.sym('http://www.w3.org/2007/ont/link#response'))\n if (!response) { break }\n var redirection = kb.any(response, kb.sym('http://www.w3.org/2007/ont/http#status'))\n if (!redirection) { break }\n if (redirection !== '301' && redirection !== '302') { break }\n }\n }\n\n /**\n * Handle fetch() response\n *\n * @param response {Response} fetch() response object\n * @param docuri {string}\n * @param options {Object}\n */\n handleResponse (response, docuri, options) {\n const kb = this.store\n const headers = response.headers\n\n const reqNode = options.req\n\n const responseNode = this.saveResponseMetadata(response, options)\n\n const contentType = this.normalizedContentType(options, headers) || ''\n\n let contentLocation = headers.get('content-location')\n\n // this.fireCallbacks('recv', xhr.args)\n // this.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}])\n\n // Check for masked errors (CORS, etc)\n if (response.status === 0) {\n console.log('Masked error - status 0 for ' + docuri)\n return this.handleError(response, docuri, options)\n }\n\n if (response.status >= 400) {\n if (response.status === 404) {\n this.nonexistent[options.original.uri] = true\n this.nonexistent[docuri] = true\n }\n\n return this.saveErrorResponse(response, responseNode)\n .then(() => {\n let errorMessage = options.resource + ' ' + response.statusText\n\n return this.failFetch(options, errorMessage, response.status, response)\n })\n }\n\n var diffLocation = null\n var absContentLocation = null\n if (contentLocation) {\n absContentLocation = Uri.join(contentLocation, docuri)\n if (absContentLocation !== docuri) {\n diffLocation = absContentLocation\n }\n }\n if (response.status === 200) {\n this.addType(ns.link('Document'), reqNode, kb, docuri)\n if (diffLocation) {\n this.addType(ns.link('Document'), reqNode, kb,\n diffLocation)\n }\n\n // Before we parse new data clear old but only on 200\n if (options.clearPreviousData) {\n kb.removeDocument(options.resource)\n }\n\n let isImage = contentType.includes('image/') ||\n contentType.includes('application/pdf')\n\n if (contentType && isImage) {\n this.addType(kb.sym('http://purl.org/dc/terms/Image'), reqNode, kb,\n docuri)\n if (diffLocation) {\n this.addType(kb.sym('http://purl.org/dc/terms/Image'), reqNode, kb,\n diffLocation)\n }\n }\n }\n\n // If we have already got the thing at this location, abort\n if (contentLocation) {\n if (!options.force && diffLocation && this.requested[absContentLocation] === 'done') {\n // we have already fetched this\n // should we smush too?\n // log.info(\"HTTP headers indicate we have already\" + \" retrieved \" +\n // xhr.resource + \" as \" + absContentLocation + \". Aborting.\")\n return this.doneFetch(options, response)\n }\n\n this.requested[absContentLocation] = true\n }\n\n this.parseLinkHeader(headers.get('link'), options.original, reqNode)\n\n let handler = this.handlerForContentType(contentType, response)\n\n if (!handler) {\n // Not a problem, we just don't extract data\n this.addStatus(reqNode, 'Fetch over. No data handled.')\n return this.doneFetch(options, response)\n }\n\n return response.text()\n .then(responseText => {\n response.responseText = responseText\n return handler.parse(this, responseText, options, response)\n })\n }\n\n saveErrorResponse (response, responseNode) {\n let kb = this.store\n\n return response.text()\n .then(content => {\n if (content.length > 10) {\n kb.add(responseNode, ns.http('content'), kb.literal(content), responseNode)\n }\n })\n }\n\n /**\n * @param contentType {string}\n *\n * @returns {Handler|null}\n */\n handlerForContentType (contentType, response) {\n if (!contentType) {\n return null\n }\n\n let Handler = this.handlers.find(handler => {\n return contentType.match(handler.pattern)\n })\n\n return Handler ? new Handler(response) : null\n }\n\n /**\n * @param uri {string}\n *\n * @returns {string}\n */\n guessContentType (uri) {\n return CONTENT_TYPE_BY_EXT[uri.split('.').pop()]\n }\n\n /**\n * @param options {Object}\n * @param headers {Headers}\n *\n * @returns {string}\n */\n normalizedContentType (options, headers) {\n if (options.forceContentType) {\n return options.forceContentType\n }\n\n let contentType = headers.get('content-type')\n if (!contentType || contentType.includes('application/octet-stream')) {\n let guess = this.guessContentType(options.resource.uri)\n\n if (guess) {\n return guess\n }\n }\n\n let protocol = Uri.protocol(options.resource.uri)\n\n if (!contentType && ['file', 'chrome'].includes(protocol)) {\n return 'text/xml'\n }\n\n return contentType\n }\n\n /**\n * Sends a new request to the specified uri. (Extracted from `onerrorFactory()`)\n *\n * @param newURI {string}\n * @param options {Object}\n *\n * @returns {Promise}\n */\n redirectToProxy (newURI, options) {\n this.addStatus(options.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>')\n\n options.proxyUsed = true\n\n const kb = this.store\n const oldReq = options.req // request metadata blank node\n\n if (!options.noMeta) {\n kb.add(oldReq, ns.link('redirectedTo'), kb.sym(newURI), oldReq)\n this.addStatus(oldReq, 'redirected to new request') // why\n }\n\n this.requested[options.resource.uri] = 'redirected'\n this.redirectedTo[options.resource.uri] = newURI\n\n let newOptions = Object.assign({}, options)\n newOptions.baseURI = options.resource.uri\n\n return this.fetchUri(newURI, newOptions)\n .then(response => {\n if (!newOptions.noMeta) {\n kb.add(oldReq, ns.link('redirectedRequest'), newOptions.req, this.appNode)\n }\n\n return response\n })\n }\n\n setRequestTimeout (uri, options) {\n return new Promise((resolve) => {\n this.timeouts[uri] = (this.timeouts[uri] || []).concat(setTimeout(() => {\n if (this.isPending(uri) &&\n !options.retriedWithNoCredentials &&\n !options.proxyUsed) {\n resolve(this.failFetch(options, `Request to ${uri} timed out`, 'timeout'))\n }\n }, this.timeout))\n })\n }\n\n addFetchCallback (uri, callback) {\n if (!this.fetchCallbacks[uri]) {\n this.fetchCallbacks[uri] = [callback]\n } else {\n this.fetchCallbacks[uri].push(callback)\n }\n }\n\n acceptString () {\n let acceptstring = ''\n\n for (let mediaType in this.mediatypes) {\n if (acceptstring !== '') {\n acceptstring += ', '\n }\n\n acceptstring += mediaType\n\n for (let property in this.mediatypes[mediaType]) {\n acceptstring += ';' + property + '=' + this.mediatypes[mediaType][property]\n }\n }\n\n return acceptstring\n }\n // var updatesVia = new $rdf.UpdatesVia(this) // Subscribe to headers\n// @@@@@@@@ This is turned off because it causes a websocket to be set up for ANY fetch\n// whether we want to track it ot not. including ontologies loaed though the XSSproxy\n}\n\nmodule.exports = Fetcher\nmodule.exports.HANDLERS = HANDLERS\nmodule.exports.CONTENT_TYPE_BY_EXT = CONTENT_TYPE_BY_EXT\n","module.exports = serialize\n\nconst convert = require('./convert')\nconst Serializer = require('./serializer')\n\n/**\n * Serialize to the appropriate format\n * @@ Currently NQuads and JSON/LD are deal with extrelemently inefficiently\n * through mutiple conversions.\n */\nfunction serialize (target, kb, base, contentType, callback, options) {\n base = base || target.uri\n options = options || {}\n contentType = contentType || 'text/turtle' // text/n3 if complex?\n var documentString = null\n try {\n var sz = Serializer(kb)\n if (options.flags) sz.setFlags(options.flags)\n var newSts = kb.statementsMatching(undefined, undefined, undefined, target)\n var n3String\n sz.suggestNamespaces(kb.namespaces)\n sz.setBase(base)\n switch (contentType) {\n case 'application/rdf+xml':\n documentString = sz.statementsToXML(newSts)\n return executeCallback(null, documentString)\n case 'text/n3':\n case 'application/n3': // Legacy\n documentString = sz.statementsToN3(newSts)\n return executeCallback(null, documentString)\n case 'text/turtle':\n case 'application/x-turtle': // Legacy\n sz.setFlags('si') // Suppress = for sameAs and => for implies\n documentString = sz.statementsToN3(newSts)\n return executeCallback(null, documentString)\n case 'application/n-triples':\n sz.setFlags('deinprstux') // Suppress nice parts of N3 to make ntriples\n documentString = sz.statementsToNTriples(newSts)\n return executeCallback(null, documentString)\n case 'application/ld+json':\n sz.setFlags('deinprstux') // Use adapters to connect to incmpatible parser\n n3String = sz.statementsToNTriples(newSts)\n // n3String = sz.statementsToN3(newSts)\n convert.convertToJson(n3String, callback)\n break\n case 'application/n-quads':\n case 'application/nquads': // @@@ just outpout the quads? Does not work for collections\n sz.setFlags('deinprstux q') // Suppress nice parts of N3 to make ntriples\n documentString = sz.statementsToNTriples(newSts) // q in flag means actually quads\n return executeCallback(null, documentString)\n // n3String = sz.statementsToN3(newSts)\n // documentString = convert.convertToNQuads(n3String, callback)\n break\n default:\n throw new Error('Serialize: Content-type ' + contentType + ' not supported for data write.')\n }\n } catch (err) {\n if (callback) {\n return callback(err)\n }\n throw err // Don't hide problems from caller in sync mode\n }\n\n function executeCallback (err, result) {\n if (callback) {\n callback(err, result)\n return\n } else {\n return result\n }\n }\n}\n","/* Serialization of RDF Graphs\n**\n** Tim Berners-Lee 2006\n** This is was http://dig.csail.mit.edu/2005/ajar/ajaw/js/rdf/serialize.js\n** This is or was https://github.com/linkeddata/rdflib.js/blob/master/src/serializer.js\n** Licence: MIT\n*/\nconst NamedNode = require('./named-node')\nconst BlankNode = require('./blank-node')\nconst Uri = require('./uri')\nconst Util = require('./util')\nconst XSD = require('./xsd')\n\nvar Serializer = (function () {\n var __Serializer = function (store) {\n this.flags = ''\n this.base = null\n\n this.prefixes = [] // suggested prefixes\n this.namespaces = [] // complementary indexes\n\n this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') // XML code assumes this!\n this.suggestPrefix('xml', 'reserved:reservedForFutureUse') // XML reserves xml: in the spec.\n\n this.namespacesUsed = [] // Count actually used and so needed in @prefixes\n this.keywords = ['a'] // The only one we generate at the moment\n this.prefixchars = 'abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n this.incoming = null // Array not calculated yet\n this.formulas = [] // remebering original formulae from hashes\n this.store = store\n }\n\n __Serializer.prototype.setBase = function (base) { this.base = base; return this }\n\n __Serializer.prototype.setFlags = function (flags) { this.flags = flags || ''; return this }\n\n __Serializer.prototype.toStr = function (x) {\n var s = x.toNT()\n if (x.termType === 'Graph') {\n this.formulas[s] = x // remember as reverse does not work\n }\n return s\n }\n\n __Serializer.prototype.fromStr = function (s) {\n if (s[0] === '{') {\n var x = this.formulas[s]\n if (!x) console.log('No formula object for ' + s)\n return x\n }\n return this.store.fromNT(s)\n }\n /* Accumulate Namespaces\n **\n ** These are only hints. If two overlap, only one gets used\n ** There is therefore no guarantee in general.\n */\n __Serializer.prototype.suggestPrefix = function (prefix, uri) {\n if (prefix.slice(0, 7) === 'default') return // Try to weed these out\n if (prefix.slice(0, 2) === 'ns') return // From others inferior algos\n if (!prefix || !uri) return // empty strings not suitable\n if (prefix in this.namespaces || uri in this.prefixes) return // already used\n this.prefixes[uri] = prefix\n this.namespaces[prefix] = uri\n }\n\n // Takes a namespace -> prefix map\n __Serializer.prototype.suggestNamespaces = function (namespaces) {\n for (var px in namespaces) {\n this.suggestPrefix(px, namespaces[px])\n return this\n }\n }\n\n __Serializer.prototype.checkIntegrity = function () {\n var p, ns\n for (p in this.namespaces) {\n if (this.prefixes[this.namespaces[p]] !== p) {\n throw new Error('Serializer integity error 1: ' + p + ', ' +\n this.namespaces[p] + ', ' + this.prefixes[this.namespaces[p]] + '!')\n }\n }\n for (ns in this.prefixes) {\n if (this.namespaces[this.prefixes[ns]] !== ns) {\n throw new Error('Serializer integity error 2: ' + ns + ', ' +\n this.prefixs[ns] + ', ' + this.namespaces[this.prefixes[ns]] + '!')\n }\n }\n }\n\n // Make up an unused prefix for a random namespace\n __Serializer.prototype.makeUpPrefix = function (uri) {\n var p = uri\n function canUseMethod (pp) {\n if (!__Serializer.prototype.validPrefix.test(pp)) return false // bad format\n if (pp === 'ns') return false // boring\n if (pp in this.namespaces) return false // already used\n this.prefixes[uri] = pp\n this.namespaces[pp] = uri\n return pp\n }\n var canUse = canUseMethod.bind(this)\n\n if ('#/'.indexOf(p[p.length - 1]) >= 0) p = p.slice(0, -1)\n var slash = p.lastIndexOf('/')\n if (slash >= 0) p = p.slice(slash + 1)\n var i = 0\n while (i < p.length) {\n if (this.prefixchars.indexOf(p[i])) {\n i++\n } else {\n break\n }\n }\n p = p.slice(0, i)\n\n if (p.length < 6 && (canUse(p))) return p // exact is best\n if (canUse(p.slice(0, 3))) return p.slice(0, 3)\n if (canUse(p.slice(0, 2))) return p.slice(0, 2)\n if (canUse(p.slice(0, 4))) return p.slice(0, 4)\n if (canUse(p.slice(0, 1))) return p.slice(0, 1)\n if (canUse(p.slice(0, 5))) return p.slice(0, 5)\n if (!__Serializer.prototype.validPrefix.test(p)) {\n p = 'n' // Otherwise the loop below may never termimnate\n }\n for (var j = 0; ; j++) if (canUse(p.slice(0, 3) + j)) return p.slice(0, 3) + j\n }\n\n __Serializer.prototype.rootSubjects = function (sts) {\n var incoming = {}\n var subjects = {}\n var allBnodes = {}\n\n /* This scan is to find out which nodes will have to be the roots of trees\n ** in the serialized form. This will be any symbols, and any bnodes\n ** which hve more or less than one incoming arc, and any bnodes which have\n ** one incoming arc but it is an uninterrupted loop of such nodes back to itself.\n ** This should be kept linear time with repect to the number of statements.\n ** Note it does not use any indexing of the store.\n */\n for (var i = 0; i < sts.length; i++) {\n var st = sts[i]\n var checkMentions = function (x) {\n if (!incoming.hasOwnProperty(x)) incoming[x] = []\n incoming[x].push(st.subject) // List of things which will cause this to be printed\n }\n var st2 = [st.subject, st.predicate, st.object]\n st2.map(function (y) {\n if (y.termType === 'BlankNode') {\n allBnodes[y.toNT()] = true\n } else if (y.termType === 'Collection') {\n y.elements.forEach(function (z) {\n checkMentions(z) // bnodes in collections important\n })\n }\n })\n checkMentions(sts[i].object)\n var ss = subjects[this.toStr(st.subject)] // Statements with this as subject\n if (!ss) ss = []\n ss.push(st)\n subjects[this.toStr(st.subject)] = ss // Make hash. @@ too slow for formula?\n }\n\n var roots = []\n for (var xNT in subjects) {\n if (!subjects.hasOwnProperty(xNT)) continue\n var y = this.fromStr(xNT)\n if ((y.termType !== 'BlankNode') || !incoming[y] || (incoming[y].length !== 1)) {\n roots.push(y)\n continue\n }\n }\n this.incoming = incoming // Keep for serializing @@ Bug for nested formulas\n\n // Now do the scan using existing roots\n var rootsHash = {}\n for (var k = 0; k < roots.length; k++) {\n rootsHash[roots[k].toNT()] = true\n }\n return {'roots': roots, 'subjects': subjects,\n 'rootsHash': rootsHash, 'incoming': incoming}\n }\n\n // //////////////////////////////////////////////////////\n\n __Serializer.prototype.toN3 = function (f) {\n return this.statementsToN3(f.statements)\n }\n\n __Serializer.prototype._notQNameChars = '\\t\\r\\n !\"#$%&\\'()*.,+/;<=>?@[\\\\]^`{|}~'\n __Serializer.prototype._notNameChars =\n (__Serializer.prototype._notQNameChars + ':')\n\n __Serializer.prototype.explicitURI = function (uri) {\n if (this.flags.indexOf('r') < 0 && this.base) {\n uri = Uri.refTo(this.base, uri)\n } else if (this.flags.indexOf('u') >= 0) { // Unicode encoding NTriples style\n uri = backslashUify(uri)\n } else {\n uri = hexify(uri)\n }\n return '<' + uri + '>'\n }\n\n __Serializer.prototype.statementsToNTriples = function (sts) {\n var sorted = sts.slice()\n sorted.sort()\n var str = ''\n var rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'\n var self = this\n var kb = this.store\n var termToNT = function (x) {\n if (x.termType !== 'Collection') {\n return self.atomicTermToN3(x)\n }\n var list = x.elements\n var rest = kb.sym(rdfns + 'nill')\n for (var i = list.length - 1; i >= 0; i--) {\n var bnode = new BlankNode()\n str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'first')) + ' ' + termToNT(list[i]) + '.\\n'\n str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'rest')) + ' ' + termToNT(rest) + '.\\n'\n rest = bnode\n }\n return self.atomicTermToN3(rest)\n }\n for (var i = 0; i < sorted.length; i++) {\n var st = sorted[i]\n var s = ''\n s += termToNT(st.subject) + ' '\n s += termToNT(st.predicate) + ' '\n s += termToNT(st.object) + ' '\n if (this.flags.indexOf('q') >= 0) { // Do quads not nrtiples\n s += termToNT(st.why) + ' '\n }\n s += '.\\n'\n str += s\n }\n return str\n }\n\n __Serializer.prototype.statementsToN3 = function (sts) {\n var indent = 4\n var width = 80\n var kb = this.store\n // A URI Map alows us to put the type statemnts at the top.\n var uriMap = {'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': 'aaa:00'}\n var SPO = function (x, y) { // Do limited canonicalization of bnodes\n return Util.heavyCompareSPO(x, y, kb, uriMap)\n }\n sts.sort(SPO)\n\n if (this.base && !this.defaultNamespace){\n this.defaultNamespace = this.base + '#'\n }\n\n var predMap = {}\n if (this.flags.indexOf('s') < 0) {\n predMap['http://www.w3.org/2002/07/owl#sameAs'] = '='\n }\n if (this.flags.indexOf('t') < 0) {\n predMap['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] = 'a'\n }\n if (this.flags.indexOf('i') < 0) {\n predMap['http://www.w3.org/2000/10/swap/log#implies'] = '=>'\n }\n // //////////////////////// Arrange the bits of text\n\n var spaces = function (n) {\n var s = ''\n for (var i = 0; i < n; i++) s += ' '\n return s\n }\n\n var treeToLine = function (tree) {\n var str = ''\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n var s2 = (typeof branch === 'string') ? branch : treeToLine(branch)\n // Note the space before the dot in case statement ends 123. which is in fact allowed but be conservative.\n if (i !== 0) {\n var ch = str.slice(-1) || ' '\n if (s2 === ',' || s2 === ';') {\n // no gap\n } else if (s2 === '.' && !('0123456789.'.includes(ch))) { // no gap except after number\n // no gap\n } else {\n str += ' ' // separate from previous token\n }\n }\n str += s2\n }\n return str\n }\n\n // Convert a nested tree of lists and strings to a string\n var treeToString = function (tree, level) {\n var str = ''\n var lastLength = 100000\n if (level === undefined) level = -1\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n if (typeof branch !== 'string') {\n var substr = treeToString(branch, level + 1)\n if (\n substr.length < 10 * (width - indent * level) &&\n substr.indexOf('\"\"\"') < 0) { // Don't mess up multiline strings\n var line = treeToLine(branch)\n if (line.length < (width - indent * level)) {\n branch = line // Note! treat as string below\n substr = ''\n }\n }\n if (substr) lastLength = 10000\n str += substr\n }\n if (typeof branch === 'string') {\n if (branch.length === 1 && str.slice(-1) === '\\n') {\n if (',.;'.indexOf(branch) >= 0) {\n str = str.slice(0, -1) + branch + '\\n' // slip punct'n on end\n lastLength += 1\n continue\n }\n }\n if (lastLength < (indent * level + 4) || // if new line not necessary\n lastLength + branch.length + 1 < width && ';.'.indexOf(str[str.length - 2]) < 0) { // or the string fits on last line\n str = str.slice(0, -1) + ' ' + branch + '\\n' // then continue on this line\n lastLength += branch.length + 1\n } else {\n let line = spaces(indent * level) + branch\n str += line + '\\n'\n lastLength = line.length\n if (level < 0) {\n str += '\\n' // extra blank line\n lastLength = 100000 // don't touch\n }\n }\n }\n }\n return str\n }\n\n // //////////////////////////////////////////// Structure for N3\n // Convert a set of statements into a nested tree of lists and strings\n function statementListToTreeMethod (statements) {\n var stats = this.rootSubjects(statements)\n var roots = stats.roots\n var results = []\n for (var i = 0; i < roots.length; i++) {\n var root = roots[i]\n results.push(subjectTree(root, stats))\n }\n return results\n }\n var statementListToTree = statementListToTreeMethod.bind(this)\n\n // The tree for a subject\n function subjectTree (subject, stats) {\n if (subject.termType === 'BlankNode' && !stats.incoming[subject]) {\n return objectTree(subject, stats, true).concat(['.']) // Anonymous bnode subject\n }\n return [ termToN3(subject, stats) ].concat([propertyTree(subject, stats)]).concat(['.'])\n }\n // The property tree for a single subject or anonymous node\n function propertyTreeMethod (subject, stats) {\n var results = []\n var lastPred = null\n var sts = stats.subjects[this.toStr(subject)] || [] // relevant statements\n if (typeof sts === 'undefined') {\n throw new Error('Cant find statements for ' + subject)\n }\n\n var objects = []\n for (var i = 0; i < sts.length; i++) {\n var st = sts[i]\n if (st.predicate.uri === lastPred) {\n objects.push(',')\n } else {\n if (lastPred) {\n results = results.concat([objects]).concat([';'])\n objects = []\n }\n results.push(predMap[st.predicate.uri]\n ? predMap[st.predicate.uri] : termToN3(st.predicate, stats))\n }\n lastPred = st.predicate.uri\n objects.push(objectTree(st.object, stats))\n }\n results = results.concat([objects])\n return results\n }\n var propertyTree = propertyTreeMethod.bind(this)\n\n function objectTreeMethod (obj, stats, force) {\n if (obj.termType === 'BlankNode' &&\n (force || stats.rootsHash[obj.toNT()] === undefined)) {// if not a root\n if (stats.subjects[this.toStr(obj)]) {\n return ['[', propertyTree(obj, stats), ']']\n } else {\n return '[]'\n }\n }\n return termToN3(obj, stats)\n }\n var objectTree = objectTreeMethod.bind(this)\n\n function termToN3Method (expr, stats) { //\n var i, res\n switch (expr.termType) {\n case 'Graph':\n res = ['{']\n res = res.concat(statementListToTree(expr.statements))\n return res.concat(['}'])\n\n case 'Collection':\n res = ['(']\n for (i = 0; i < expr.elements.length; i++) {\n res.push([ objectTree(expr.elements[i], stats) ])\n }\n res.push(')')\n return res\n\n default:\n return this.atomicTermToN3(expr)\n }\n }\n __Serializer.prototype.termToN3 = termToN3\n var termToN3 = termToN3Method.bind(this)\n\n function prefixDirectivesMethod () {\n var str = ''\n if (this.defaultNamespace) {\n str += '@prefix : ' + this.explicitURI(this.defaultNamespace) + '.\\n'\n }\n for (var ns in this.prefixes) {\n if (!this.prefixes.hasOwnProperty(ns)) continue\n if (!this.namespacesUsed[ns]) continue\n str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) +\n '.\\n'\n }\n return str + '\\n'\n }\n var prefixDirectives = prefixDirectivesMethod.bind(this)\n // Body of statementsToN3:\n var tree = statementListToTree(sts)\n return prefixDirectives() + treeToString(tree)\n }\n // //////////////////////////////////////////// Atomic Terms\n\n // Deal with term level things and nesting with no bnode structure\n __Serializer.prototype.atomicTermToN3 = function atomicTermToN3 (expr, stats) {\n switch (expr.termType) {\n case 'BlankNode':\n case 'Variable':\n return expr.toNT()\n case 'Literal':\n var val = expr.value\n if (typeof val !== 'string') {\n throw new TypeError('Value of RDF literal node must be a string')\n }\n // var val = expr.value.toString() // should be a string already\n if (expr.datatype && this.flags.indexOf('x') < 0) { // Supress native numbers\n switch (expr.datatype.uri) {\n\n case 'http://www.w3.org/2001/XMLSchema#integer':\n return val\n\n case 'http://www.w3.org/2001/XMLSchema#decimal': // In urtle must have dot\n if (val.indexOf('.') < 0) val += '.0'\n return val\n\n case 'http://www.w3.org/2001/XMLSchema#double': // Must force use of 'e'\n if (val.indexOf('.') < 0) val += '.0'\n if (val.indexOf('e') < 0) val += 'e0'\n return val\n\n case 'http://www.w3.org/2001/XMLSchema#boolean':\n return expr.value === '1' ? 'true' : 'false'\n }\n }\n var str = this.stringToN3(expr.value)\n if (expr.language) {\n str += '@' + expr.language\n } else if (!expr.datatype.equals(XSD.string)) {\n str += '^^' + this.atomicTermToN3(expr.datatype, stats)\n }\n return str\n case 'NamedNode':\n return this.symbolToN3(expr)\n default:\n throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType)\n }\n }\n\n // stringToN3: String escaping for N3\n\n __Serializer.prototype.validPrefix = new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)\n\n __Serializer.prototype.forbidden1 = new RegExp(/[\\\\\"\\b\\f\\r\\v\\t\\n\\u0080-\\uffff]/gm)\n __Serializer.prototype.forbidden3 = new RegExp(/[\\\\\"\\b\\f\\r\\v\\u0080-\\uffff]/gm)\n __Serializer.prototype.stringToN3 = function stringToN3 (str, flags) {\n if (!flags) flags = 'e'\n var res = ''\n var i, j, k\n var delim\n var forbidden\n if (str.length > 20 && // Long enough to make sense\n str.slice(-1) !== '\"' && // corner case'\n flags.indexOf('n') < 0 && // Force single line\n (str.indexOf('\\n') > 0 || str.indexOf('\"') > 0)) {\n delim = '\"\"\"'\n forbidden = __Serializer.prototype.forbidden3\n } else {\n delim = '\"'\n forbidden = __Serializer.prototype.forbidden1\n }\n for (i = 0; i < str.length;) {\n forbidden.lastIndex = 0\n var m = forbidden.exec(str.slice(i))\n if (m == null) break\n j = i + forbidden.lastIndex - 1\n res += str.slice(i, j)\n var ch = str[j]\n if (ch === '\"' && delim === '\"\"\"' && str.slice(j, j + 3) !== '\"\"\"') {\n res += ch\n } else {\n k = '\\b\\f\\r\\t\\v\\n\\\\\"'.indexOf(ch) // No escaping of bell (7)?\n if (k >= 0) {\n res += '\\\\' + 'bfrtvn\\\\\"'[k]\n } else {\n if (flags.indexOf('e') >= 0) { // Unicode escaping in strings not unix style\n res += '\\\\u' + ('000' +\n ch.charCodeAt(0).toString(16).toLowerCase()).slice(-4)\n } else { // no 'e' flag\n res += ch\n }\n }\n }\n i = j + 1\n }\n return delim + res + str.slice(i) + delim\n }\n // A single symbol, either in <> or namespace notation\n\n __Serializer.prototype.symbolToN3 = function symbolToN3 (x) { // c.f. symbolString() in notation3.py\n var uri = x.uri\n var j = uri.indexOf('#')\n if (j < 0 && this.flags.indexOf('/') < 0) {\n j = uri.lastIndexOf('/')\n }\n if (j >= 0 && this.flags.indexOf('p') < 0 &&\n // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?)\n (uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) {\n var canSplit = true\n for (var k = j + 1; k < uri.length; k++) {\n if (__Serializer.prototype._notNameChars.indexOf(uri[k]) >= 0) {\n canSplit = false\n break\n }\n }\n/*\n if (uri.slice(0, j + 1) === this.base + '#') { // base-relative\n if (canSplit) {\n return ':' + uri.slice(j + 1) // assume deafult ns is local\n } else {\n return '<#' + uri.slice(j + 1) + '>'\n }\n }\n*/\n if (canSplit) {\n var localid = uri.slice(j + 1)\n var namesp = uri.slice(0, j + 1)\n if (this.defaultNamespace && this.defaultNamespace === namesp &&\n this.flags.indexOf('d') < 0) { // d -> suppress default\n if (this.flags.indexOf('k') >= 0 &&\n this.keyords.indexOf(localid) < 0) {\n return localid\n }\n return ':' + localid\n }\n // this.checkIntegrity() // @@@ Remove when not testing\n var prefix = this.prefixes[namesp]\n if (!prefix) prefix = this.makeUpPrefix(namesp)\n if (prefix) {\n this.namespacesUsed[namesp] = true\n return prefix + ':' + localid\n }\n // Fall though if can't do qname\n }\n }\n return this.explicitURI(uri)\n }\n // String escaping utilities\n\n function hexify (str) { // also used in parser\n return encodeURI(str)\n }\n\n function backslashUify (str) {\n var res = ''\n var k\n for (var i = 0; i < str.length; i++) {\n k = str.charCodeAt(i)\n if (k > 65535) {\n res += '\\\\U' + ('00000000' + k.toString(16)).slice(-8) // convert to upper?\n } else if (k > 126) {\n res += '\\\\u' + ('0000' + k.toString(16)).slice(-4)\n } else {\n res += str[i]\n }\n }\n return res\n }\n\n // /////////////////////////// Quad store serialization\n\n // @para. write - a function taking a single string to be output\n //\n __Serializer.prototype.writeStore = function (write) {\n var kb = this.store\n var fetcher = kb.fetcher\n var session = fetcher && fetcher.appNode\n\n // The core data\n\n var sources = this.store.index[3]\n for (var s in sources) { // -> assume we can use -> as short for log:semantics\n var source = kb.fromNT(s)\n if (session && source.sameTerm(session)) continue\n write('\\n' + this.atomicTermToN3(source) + ' ' +\n this.atomicTermToN3(kb.sym('http://www.w3.org/2000/10/swap/log#semantics')) +\n ' { ' + this.statementsToN3(kb.statementsMatching(\n undefined, undefined, undefined, source)) + ' }.\\n')\n }\n\n // The metadata from HTTP interactions:\n\n kb.statementsMatching(undefined,\n kb.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(\n function (st) {\n write('\\n<' + st.object.value + '> log:metadata {\\n')\n var sts = kb.statementsMatching(undefined, undefined, undefined, st.subject)\n write(this.statementsToN3(this.statementsToN3(sts)))\n write('}.\\n')\n })\n\n // Inferences we have made ourselves not attributable to anyone else\n\n var metaSources = []\n if (session) metaSources.push(session)\n var metadata = []\n metaSources.map(function (source) {\n metadata = metadata.concat(kb.statementsMatching(undefined, undefined, undefined, source))\n })\n write(this.statementsToN3(metadata))\n }\n\n // ////////////////////////////////////////////// XML serialization\n\n __Serializer.prototype.statementsToXML = function (sts) {\n var indent = 4\n var width = 80\n\n var namespaceCounts = [] // which have been used\n namespaceCounts['http://www.w3.org/1999/02/22-rdf-syntax-ns#'] = true\n\n var liPrefix = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#_' // prefix for ordered list items\n\n // //////////////////////// Arrange the bits of XML text\n\n var spaces = function (n) {\n var s = ''\n for (var i = 0; i < n; i++) s += ' '\n return s\n }\n\n var XMLtreeToLine = function (tree) {\n var str = ''\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n var s2 = (typeof branch === 'string') ? branch : XMLtreeToLine(branch)\n str += s2\n }\n return str\n }\n\n // Convert a nested tree of lists and strings to a string\n var XMLtreeToString = function (tree, level) {\n var str = ''\n var line\n var lastLength = 100000\n if (!level) level = 0\n for (var i = 0; i < tree.length; i++) {\n var branch = tree[i]\n if (typeof branch !== 'string') {\n var substr = XMLtreeToString(branch, level + 1)\n if (\n substr.length < 10 * (width - indent * level) &&\n substr.indexOf('\"\"\"') < 0) { // Don't mess up multiline strings\n line = XMLtreeToLine(branch)\n if (line.length < (width - indent * level)) {\n branch = ' ' + line // @@ Hack: treat as string below\n substr = ''\n }\n }\n if (substr) lastLength = 10000\n str += substr\n }\n if (typeof branch === 'string') {\n if (lastLength < (indent * level + 4)) { // continue\n str = str.slice(0, -1) + ' ' + branch + '\\n'\n lastLength += branch.length + 1\n } else {\n line = spaces(indent * level) + branch\n str += line + '\\n'\n lastLength = line.length\n }\n } else { // not string\n }\n }\n return str\n }\n\n function statementListToXMLTreeMethod (statements) {\n this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n var stats = this.rootSubjects(statements)\n var roots = stats.roots\n var results = []\n for (var i = 0; i < roots.length; i++) {\n var root = roots[i]\n results.push(subjectXMLTree(root, stats))\n }\n return results\n }\n var statementListToXMLTree = statementListToXMLTreeMethod.bind(this)\n\n function escapeForXML (str) {\n if (typeof str === 'undefined') return '@@@undefined@@@@'\n return str.replace(/[&<\"]/g, function (m) {\n switch (m[0]) {\n case '&':\n return '&'\n case '<':\n return '<'\n case '\"':\n return '"' // '\n }\n })\n }\n\n function relURIMethod (term) {\n return escapeForXML((this.base) ? Util.uri.refTo(this.base, term.uri) : term.uri)\n }\n var relURI = relURIMethod.bind(this)\n\n // The tree for a subject\n function subjectXMLTreeMethod (subject, stats) {\n var results = []\n var type, t, st, pred\n var sts = stats.subjects[this.toStr(subject)] // relevant statements\n if (typeof sts === 'undefined') { // empty bnode\n return propertyXMLTree(subject, stats)\n }\n\n // Sort only on the predicate, leave the order at object\n // level undisturbed. This leaves multilingual content in\n // the order of entry (for partner literals), which helps\n // readability.\n //\n // For the predicate sort, we attempt to split the uri\n // as a hint to the sequence\n sts.sort(function (a, b) {\n var ap = a.predicate.uri\n var bp = b.predicate.uri\n if (ap.substring(0, liPrefix.length) === liPrefix || bp.substring(0, liPrefix.length) === liPrefix) { // we're only interested in sorting list items\n return ap.localeCompare(bp)\n }\n\n var as = ap.substring(liPrefix.length)\n var bs = bp.substring(liPrefix.length)\n var an = parseInt(as, 10)\n var bn = parseInt(bs, 10)\n if (isNaN(an) || isNaN(bn) ||\n an !== as || bn !== bs) { // we only care about integers\n return ap.localeCompare(bp)\n }\n\n return an - bn\n })\n\n for (var i = 0; i < sts.length; i++) {\n st = sts[i]\n // look for a type\n if (st.predicate.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && !type && st.object.termType === 'symbol') {\n type = st.object\n continue // don't include it as a child element\n }\n\n // see whether predicate can be replaced with \"li\"\n pred = st.predicate\n if (pred.uri.substr(0, liPrefix.length) === liPrefix) {\n var number = pred.uri.substr(liPrefix.length)\n // make sure these are actually numeric list items\n var intNumber = parseInt(number, 10)\n if (number === intNumber.toString()) {\n // was numeric; don't need to worry about ordering since we've already\n // sorted the statements\n pred = new NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#li')\n }\n }\n\n t = qname(pred)\n switch (st.object.termType) {\n case 'BlankNode':\n if (stats.incoming[st.object].length === 1) { // there should always be something in the incoming array for a bnode\n results = results.concat(['<' + t + ' rdf:parseType=\"Resource\">',\n subjectXMLTree(st.object, stats),\n ''])\n } else {\n results = results.concat(['<' + t + ' rdf:nodeID=\"' +\n st.object.toNT().slice(2) + '\"/>'])\n }\n break\n case 'NamedNode':\n results = results.concat(['<' + t + ' rdf:resource=\"' +\n relURI(st.object) + '\"/>'])\n break\n case 'Literal':\n results = results.concat(['<' + t +\n (st.object.datatype.equals(XSD.string)\n ? ''\n : ' rdf:datatype=\"' + escapeForXML(st.object.datatype.uri) + '\"') +\n (st.object.language ? ' xml:lang=\"' + st.object.language + '\"' : '') +\n '>' + escapeForXML(st.object.value) +\n ''])\n break\n case 'Collection':\n results = results.concat(['<' + t + ' rdf:parseType=\"Collection\">',\n collectionXMLTree(st.object, stats),\n ''])\n break\n default:\n throw new Error(\"Can't serialize object of type \" + st.object.termType + ' into XML')\n } // switch\n }\n\n var tag = type ? qname(type) : 'rdf:Description'\n\n var attrs = ''\n if (subject.termType === 'BlankNode') {\n if (!stats.incoming[subject] || stats.incoming[subject].length !== 1) { // not an anonymous bnode\n attrs = ' rdf:nodeID=\"' + subject.toNT().slice(2) + '\"'\n }\n } else {\n attrs = ' rdf:about=\"' + relURI(subject) + '\"'\n }\n\n return [ '<' + tag + attrs + '>' ].concat([results]).concat([''])\n }\n\n var subjectXMLTree = subjectXMLTreeMethod.bind(this)\n\n function collectionXMLTree (subject, stats) {\n var res = []\n for (var i = 0; i < subject.elements.length; i++) {\n res.push(subjectXMLTree(subject.elements[i], stats))\n }\n return res\n }\n\n // The property tree for a single subject or anonymos node\n function propertyXMLTreeMethod (subject, stats) {\n var results = []\n var sts = stats.subjects[this.toStr(subject)] // relevant statements\n if (!sts) return results // No relevant statements\n sts.sort()\n for (var i = 0; i < sts.length; i++) {\n var st = sts[i]\n switch (st.object.termType) {\n case 'BlankNode':\n if (stats.rootsHash[st.object.toNT()]) { // This bnode has been done as a root -- no content here @@ what bout first time\n results = results.concat(['<' + qname(st.predicate) + ' rdf:nodeID=\"' + st.object.toNT().slice(2) + '\">',\n ''])\n } else {\n results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType=\"Resource\">',\n propertyXMLTree(st.object, stats),\n ''])\n }\n break\n case 'NamedNode':\n results = results.concat(['<' + qname(st.predicate) + ' rdf:resource=\"' +\n relURI(st.object) + '\"/>'])\n break\n case 'Literal':\n results = results.concat(['<' + qname(st.predicate) +\n (st.object.datatype.equals(XSD.string) ? '' : ' rdf:datatype=\"' + escapeForXML(st.object.datatype.value) + '\"') +\n (st.object.language ? ' xml:lang=\"' + st.object.language + '\"' : '') +\n '>' + escapeForXML(st.object.value) +\n ''])\n break\n case 'Collection':\n results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType=\"Collection\">',\n collectionXMLTree(st.object, stats),\n ''])\n break\n default:\n throw new Error(\"Can't serialize object of type \" + st.object.termType + ' into XML')\n } // switch\n }\n return results\n }\n var propertyXMLTree = propertyXMLTreeMethod.bind(this)\n\n function qnameMethod (term) {\n var uri = term.uri\n\n var j = uri.indexOf('#')\n if (j < 0 && this.flags.indexOf('/') < 0) {\n j = uri.lastIndexOf('/')\n }\n if (j < 0) throw new Error('Cannot make qname out of <' + uri + '>')\n\n for (var k = j + 1; k < uri.length; k++) {\n if (__Serializer.prototype._notNameChars.indexOf(uri[k]) >= 0) {\n throw new Error('Invalid character \"' + uri[k] + '\" cannot be in XML qname for URI: ' + uri)\n }\n }\n var localid = uri.slice(j + 1)\n var namesp = uri.slice(0, j + 1)\n if (this.defaultNamespace && this.defaultNamespace === namesp &&\n this.flags.indexOf('d') < 0) { // d -> suppress default\n return localid\n }\n var prefix = this.prefixes[namesp]\n if (!prefix) prefix = this.makeUpPrefix(namesp)\n namespaceCounts[namesp] = true\n return prefix + ':' + localid\n }\n var qname = qnameMethod.bind(this)\n\n // Body of toXML:\n\n var tree = statementListToXMLTree(sts)\n var str = ''] // @@ namespace declrations\n return XMLtreeToString(tree2, -1)\n } // End @@ body\n\n var Serializer = function (store) { return new __Serializer(store) }\n return Serializer\n}())\n\nmodule.exports = Serializer\n","// RDFa Parser for rdflib.js\n\n// Originally by: Alex Milowski\n// From https://github.com/alexmilowski/green-turtle\n// Converted: timbl 2015-08-25 not yet working\n// Added wrapper: csarven 2016-05-09 working\n\n// RDFaProcessor.prototype = new Object() // Was URIResolver\n\n// RDFaProcessor.prototype.constructor=RDFaProcessor\n\n// options.base = base URI not really an option, shopuld always be set.\n//\n\nconst BlankNode = require('./blank-node')\nconst Literal = require('./literal')\nconst rdf = require('./data-factory')\nconst NamedNode = require('./named-node')\nconst Uri = require('./uri')\nconst Util = require('./util')\n\nif (typeof Node === 'undefined') { // @@@@@@ Global. Interface to xmldom.\n var Node = {\n ELEMENT_NODE: 1,\n ATTRIBUTE_NODE: 2,\n TEXT_NODE: 3,\n CDATA_SECTION_NODE: 4,\n ENTITY_REFERENCE_NODE: 5,\n ENTITY_NODE: 6,\n PROCESSING_INSTRUCTION_NODE: 7,\n COMMENT_NODE: 8,\n DOCUMENT_NODE: 9,\n DOCUMENT_TYPE_NODE: 10,\n DOCUMENT_FRAGMENT_NODE: 11,\n NOTATION_NODE: 12\n }\n}\n\nclass RDFaProcessor {\n constructor (kb, options) {\n this.options = options || {}\n this.kb = kb\n this.target = options.target || {\n graph: {\n subjects: {},\n prefixes: {},\n terms: {}\n }\n }\n // XXX: Added to track bnodes\n this.blankNodes = []\n // XXX: Added for normalisation\n this.htmlOptions = {\n 'selfClosing': 'br img input area base basefont col colgroup source wbr isindex link meta param hr'\n }\n this.theOne = '_:' + (new Date()).getTime()\n this.language = null\n this.vocabulary = null\n this.blankCounter = 0\n this.langAttributes = [ { namespaceURI: 'http://www.w3.org/XML/1998/namespace', localName: 'lang' } ]\n this.inXHTMLMode = false\n this.absURIRE = /[\\w\\_\\-]+:\\S+/\n this.finishedHandlers = []\n this.init()\n }\n\n addTriple (origin, subject, predicate, object) {\n var su, ob, pr, or\n if (typeof subject === 'undefined') {\n su = rdf.namedNode(this.options.base)\n } else {\n su = this.toRDFNodeObject(subject)\n }\n pr = this.toRDFNodeObject(predicate)\n ob = this.toRDFNodeObject(object)\n or = rdf.namedNode(this.options.base)\n // console.log('Adding { ' + su + ' ' + pr + ' ' + ob + ' ' + or + ' }')\n this.kb.add(su, pr, ob, or)\n }\n\n ancestorPath (node) {\n var path = ''\n while (node && node.nodeType !== Node.DOCUMENT_NODE) {\n path = '/' + node.localName + path\n node = node.parentNode\n }\n return path\n }\n\n copyMappings (mappings) {\n var newMappings = {}\n for (var k in mappings) {\n newMappings[k] = mappings[k]\n }\n return newMappings\n }\n\n copyProperties () {\n }\n\n deriveDateTimeType (value) {\n for (var i = 0; i < RDFaProcessor.dateTimeTypes.length; i++) {\n // console.log(\"Checking \"+value+\" against \"+RDFaProcessor.dateTimeTypes[i].type)\n var matched = RDFaProcessor.dateTimeTypes[i].pattern.exec(value)\n if (matched && matched[0].length === value.length) {\n // console.log(\"Matched!\")\n return RDFaProcessor.dateTimeTypes[i].type\n }\n }\n return null\n }\n\n init () {\n }\n\n newBlankNode () {\n this.blankCounter++\n return '_:' + this.blankCounter\n }\n\n newSubjectOrigin (origin, subject) {\n }\n\n parseCURIE (value, prefixes, base) {\n var colon = value.indexOf(':')\n var uri\n if (colon >= 0) {\n var prefix = value.substring(0, colon)\n if (prefix === '') {\n // default prefix\n uri = prefixes['']\n return uri ? uri + value.substring(colon + 1) : null\n } else if (prefix === '_') {\n // blank node\n return '_:' + value.substring(colon + 1)\n } else if (RDFaProcessor.NCNAME.test(prefix)) {\n uri = prefixes[prefix]\n if (uri) {\n return uri + value.substring(colon + 1)\n }\n }\n }\n return null\n }\n\n parseCURIEOrURI (value, prefixes, base) {\n var curie = this.parseCURIE(value, prefixes, base)\n if (curie) {\n return curie\n }\n return this.resolveAndNormalize(base, value)\n }\n\n parsePredicate (value, defaultVocabulary, terms, prefixes, base,\n ignoreTerms) {\n if (value === '') {\n return null\n }\n var predicate = this.parseTermOrCURIEOrAbsURI(value, defaultVocabulary, ignoreTerms ? null : terms, prefixes, base)\n if (predicate && predicate.indexOf('_:') === 0) {\n return null\n }\n return predicate\n }\n\n parsePrefixMappings (str, target) {\n var values = this.tokenize(str)\n var prefix = null\n // var uri = null\n for (var i = 0; i < values.length; i++) {\n if (values[i][values[i].length - 1] === ':') {\n prefix = values[i].substring(0, values[i].length - 1)\n } else if (prefix) {\n target[prefix] = this.options.base ? Uri.join(values[i], this.options.base) : values[i]\n prefix = null\n }\n }\n }\n\n static parseRDFaDOM (dom, kb, base) {\n var p = new RDFaProcessor(kb, { 'base': base })\n dom.baseURI = base\n p.process(dom)\n }\n\n parseSafeCURIEOrCURIEOrURI (value, prefixes, base) {\n value = this.trim(value)\n if (value.charAt(0) === '[' && value.charAt(value.length - 1) === ']') {\n value = value.substring(1, value.length - 1)\n value = value.trim(value)\n if (value.length === 0) {\n return null\n }\n if (value === '_:') {\n // the one node\n return this.theOne\n }\n return this.parseCURIE(value, prefixes, base)\n } else {\n return this.parseCURIEOrURI(value, prefixes, base)\n }\n }\n\n parseTermOrCURIEOrAbsURI (value, defaultVocabulary, terms, prefixes, base) {\n // alert(\"Parsing \"+value+\" with default vocab \"+defaultVocabulary)\n value = this.trim(value)\n var curie = this.parseCURIE(value, prefixes, base)\n if (curie) {\n return curie\n } else if (terms) {\n if (defaultVocabulary && !this.absURIRE.exec(value)) {\n return defaultVocabulary + value\n }\n var term = terms[value]\n if (term) {\n return term\n }\n var lcvalue = value.toLowerCase()\n term = terms[lcvalue]\n if (term) {\n return term\n }\n }\n if (this.absURIRE.exec(value)) {\n return this.resolveAndNormalize(base, value)\n }\n return null\n }\n\n parseTermOrCURIEOrURI (value, defaultVocabulary, terms, prefixes, base) {\n // alert(\"Parsing \"+value+\" with default vocab \"+defaultVocabulary)\n value = this.trim(value)\n var curie = this.parseCURIE(value, prefixes, base)\n if (curie) {\n return curie\n } else {\n var term = terms[value]\n if (term) {\n return term\n }\n var lcvalue = value.toLowerCase()\n term = terms[lcvalue]\n if (term) {\n return term\n }\n if (defaultVocabulary && !this.absURIRE.exec(value)) {\n return defaultVocabulary + value\n }\n }\n return this.resolveAndNormalize(base, value)\n }\n\n parseURI (uri) {\n return uri // We just use strings as URIs, not objects now.\n }\n\n process (node, options) {\n /*\n if (!window.console) {\n window.console = { log: function() {} }\n }*/\n var base\n if (node.nodeType === Node.DOCUMENT_NODE) {\n base = node.baseURI\n node = node.documentElement\n node.baseURI = base\n this.setContext(node)\n } else if (node.parentNode.nodeType === Node.DOCUMENT_NODE) {\n this.setContext(node)\n }\n var queue = []\n // Fix for Firefox that includes the hash in the base URI\n var removeHash = function (baseURI) {\n // Fix for undefined baseURI property\n if (!baseURI && options && options.baseURI) {\n return options.baseURI\n }\n\n var hash = baseURI.indexOf('#')\n if (hash >= 0) {\n baseURI = baseURI.substring(0, hash)\n }\n if (options && options.baseURIMap) {\n baseURI = options.baseURIMap(baseURI)\n }\n return baseURI\n }\n queue.push({ current: node,\n context: this.push(null, removeHash(node.baseURI))\n })\n while (queue.length > 0) {\n var item = queue.shift()\n if (item.parent) {\n // Sequence Step 14: list triple generation\n if (item.context.parent && item.context.parent.listMapping === item.listMapping) {\n // Skip a child context with exactly the same mapping\n continue\n }\n // console.log(\"Generating lists for \"+item.subject+\", tag \"+item.parent.localName)\n for (let predicate in item.listMapping) {\n var list = item.listMapping[predicate]\n if (list.length === 0) {\n this.addTriple(item.parent, item.subject, predicate, { type: RDFaProcessor.objectURI, value: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' })\n continue\n }\n var bnodes = []\n for (let i = 0; i < list.length; i++) {\n bnodes.push(this.newBlankNode())\n // this.newSubject(item.parent,bnodes[i])\n }\n for (let i = 0; i < bnodes.length; i++) {\n this.addTriple(item.parent, bnodes[i], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first', list[i])\n this.addTriple(item.parent, bnodes[i], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest', { type: RDFaProcessor.objectURI, value: (i + 1) < bnodes.length ? bnodes[i + 1] : 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' })\n }\n this.addTriple(item.parent, item.subject, predicate, { type: RDFaProcessor.objectURI, value: bnodes[0] })\n }\n continue\n }\n var current = item.current\n var context = item.context\n // console.log(\"Tag: \"+current.localName+\", listMapping=\"+JSON.stringify(context.listMapping))\n // Sequence Step 1\n var skip = false\n var newSubject = null\n var currentObjectResource = null\n var typedResource = null\n var prefixes = context.prefixes\n var prefixesCopied = false\n var incomplete = []\n var listMapping = context.listMapping\n var listMappingDifferent = !context.parent\n var language = context.language\n var vocabulary = context.vocabulary\n // TODO: the \"base\" element may be used for HTML+RDFa 1.1\n base = this.parseURI(removeHash(current.baseURI))\n current.item = null\n // Sequence Step 2: set the default vocabulary\n var vocabAtt = current.getAttributeNode('vocab')\n if (vocabAtt) {\n let value = this.trim(vocabAtt.value)\n if (value.length > 0) {\n vocabulary = value\n var baseSubject = base.spec\n // this.newSubject(current,baseSubject)\n this.addTriple(current, baseSubject, 'http://www.w3.org/ns/rdfa#usesVocabulary', { type: RDFaProcessor.objectURI, value: vocabulary })\n } else {\n vocabulary = this.vocabulary\n }\n }\n // Sequence Step 3: IRI mappings\n // handle xmlns attributes\n for (var i = 0; i < current.attributes.length; i++) {\n var att = current.attributes[i]\n // if (att.namespaceURI==\"http://www.w3.org/2000/xmlns/\") {\n if (att.nodeName.charAt(0) === 'x' && att.nodeName.indexOf('xmlns:') === 0) {\n if (!prefixesCopied) {\n prefixes = this.copyMappings(prefixes)\n prefixesCopied = true\n }\n var prefix = att.nodeName.substring(6)\n // TODO: resolve relative?\n var ref = RDFaProcessor.trim(att.value)\n prefixes[prefix] = this.options.base ? Uri.join(ref, this.options.base) : ref\n }\n }\n // Handle prefix mappings (@prefix)\n var prefixAtt = current.getAttributeNode('prefix')\n if (prefixAtt) {\n if (!prefixesCopied) {\n prefixes = this.copyMappings(prefixes)\n prefixesCopied = true\n }\n this.parsePrefixMappings(prefixAtt.value, prefixes)\n }\n // Sequence Step 4: language\n var xmlLangAtt = null\n for (let i = 0; !xmlLangAtt && i < this.langAttributes.length; i++) {\n xmlLangAtt = current.getAttributeNodeNS(this.langAttributes[i].namespaceURI, this.langAttributes[i].localName)\n }\n if (xmlLangAtt) {\n let value = RDFaProcessor.trim(xmlLangAtt.value)\n if (value.length > 0) {\n language = value\n } else {\n language = null\n }\n }\n var relAtt = current.getAttributeNode('rel')\n var revAtt = current.getAttributeNode('rev')\n var typeofAtt = current.getAttributeNode('typeof')\n var propertyAtt = current.getAttributeNode('property')\n var datatypeAtt = current.getAttributeNode('datatype')\n var datetimeAtt = this.inHTMLMode\n ? current.getAttributeNode('datetime')\n : null\n var contentAtt = current.getAttributeNode('content')\n var aboutAtt = current.getAttributeNode('about')\n var srcAtt = current.getAttributeNode('src')\n var resourceAtt = current.getAttributeNode('resource')\n var hrefAtt = current.getAttributeNode('href')\n var inlistAtt = current.getAttributeNode('inlist')\n var relAttPredicates = []\n var predicate, values\n if (relAtt) {\n values = this.tokenize(relAtt.value)\n for (let i = 0; i < values.length; i++) {\n predicate = this.parsePredicate(values[i], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt !== null)\n if (predicate) {\n relAttPredicates.push(predicate)\n }\n }\n }\n var revAttPredicates = []\n if (revAtt) {\n values = this.tokenize(revAtt.value)\n for (let i = 0; i < values.length; i++) {\n predicate = this.parsePredicate(values[i], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt)\n if (predicate) {\n revAttPredicates.push(predicate)\n }\n }\n }\n // Section 3.1, bullet 7\n if (this.inHTMLMode && (relAtt || revAtt) && propertyAtt) {\n if (relAttPredicates.length === 0) {\n relAtt = null\n }\n if (revAttPredicates.length === 0) {\n revAtt = null\n }\n }\n if (relAtt || revAtt) {\n // Sequence Step 6: establish new subject and value\n if (aboutAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base)\n }\n if (typeofAtt) {\n typedResource = newSubject\n }\n if (!newSubject) {\n if (current.parentNode.nodeType === Node.DOCUMENT_NODE) {\n newSubject = removeHash(current.baseURI)\n } else if (context.parentObject) {\n // 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\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n }\n }\n if (resourceAtt) {\n currentObjectResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!currentObjectResource) {\n if (hrefAtt) {\n currentObjectResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n } else if (srcAtt) {\n currentObjectResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n } else if (typeofAtt && !aboutAtt && !(this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body'))) {\n currentObjectResource = this.newBlankNode()\n }\n }\n if (typeofAtt && !aboutAtt && this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body')) {\n typedResource = newSubject\n } else if (typeofAtt && !aboutAtt) {\n typedResource = currentObjectResource\n }\n } else if (propertyAtt && !contentAtt && !datatypeAtt) {\n // Sequence Step 5.1: establish a new subject\n if (aboutAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base)\n if (typeofAtt) {\n typedResource = newSubject\n }\n }\n if (!newSubject && current.parentNode.nodeType === Node.DOCUMENT_NODE) {\n newSubject = removeHash(current.baseURI)\n if (typeofAtt) {\n typedResource = newSubject\n }\n } else if (!newSubject && context.parentObject) {\n // 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\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n }\n if (typeofAtt && !typedResource) {\n if (resourceAtt) {\n typedResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!typedResource && hrefAtt) {\n typedResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n }\n if (!typedResource && srcAtt) {\n typedResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n }\n if (!typedResource && (this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) {\n typedResource = newSubject\n }\n if (!typedResource) {\n typedResource = this.newBlankNode()\n }\n currentObjectResource = typedResource\n }\n // console.log(current.localName+\", newSubject=\"+newSubject+\", typedResource=\"+typedResource+\", currentObjectResource=\"+currentObjectResource)\n } else {\n // Sequence Step 5.2: establish a new subject\n if (aboutAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base)\n }\n if (!newSubject && resourceAtt) {\n newSubject = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!newSubject && hrefAtt) {\n newSubject = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n }\n if (!newSubject && srcAtt) {\n newSubject = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n }\n if (!newSubject) {\n if (current.parentNode.nodeType === Node.DOCUMENT_NODE) {\n newSubject = removeHash(current.baseURI)\n } else if ((this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) {\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n } else if (typeofAtt) {\n newSubject = this.newBlankNode()\n } else if (context.parentObject) {\n // 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\n newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n if (!propertyAtt) {\n skip = true\n }\n }\n }\n if (typeofAtt) {\n typedResource = newSubject\n }\n }\n // console.log(current.tagName+\": newSubject=\"+newSubject+\", currentObjectResource=\"+currentObjectResource+\", typedResource=\"+typedResource+\", skip=\"+skip)\n // var rdfaData = null\n if (newSubject) {\n // this.newSubject(current,newSubject)\n if (aboutAtt || resourceAtt || typedResource) {\n var id = newSubject\n if (typeofAtt && !aboutAtt && !resourceAtt && currentObjectResource) {\n id = currentObjectResource\n }\n // console.log(\"Setting data attribute for \"+current.localName+\" for subject \"+id)\n this.newSubjectOrigin(current, id)\n }\n }\n // Sequence Step 7: generate type triple\n if (typedResource) {\n values = this.tokenize(typeofAtt.value)\n for (let i = 0; i < values.length; i++) {\n var object = this.parseTermOrCURIEOrAbsURI(values[i], vocabulary, context.terms, prefixes, base)\n if (object) {\n this.addTriple(current, typedResource, RDFaProcessor.typeURI, { type: RDFaProcessor.objectURI, value: object })\n }\n }\n }\n // Sequence Step 8: new list mappings if there is a new subject\n // console.log(\"Step 8: newSubject=\"+newSubject+\", context.parentObject=\"+context.parentObject)\n if (newSubject && newSubject !== context.parentObject) {\n // console.log(\"Generating new list mapping for \"+newSubject)\n listMapping = {}\n listMappingDifferent = true\n }\n // Sequence Step 9: generate object triple\n if (currentObjectResource) {\n if (relAtt && inlistAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n let list = listMapping[relAttPredicates[i]]\n if (!list) {\n list = []\n listMapping[relAttPredicates[i]] = list\n }\n list.push({ type: RDFaProcessor.objectURI, value: currentObjectResource })\n }\n } else if (relAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n this.addTriple(current, newSubject, relAttPredicates[i], { type: RDFaProcessor.objectURI, value: currentObjectResource })\n }\n }\n if (revAtt) {\n for (let i = 0; i < revAttPredicates.length; i++) {\n this.addTriple(current, currentObjectResource, revAttPredicates[i], { type: RDFaProcessor.objectURI, value: newSubject })\n }\n }\n } else {\n // Sequence Step 10: incomplete triples\n if (newSubject && !currentObjectResource && (relAtt || revAtt)) {\n currentObjectResource = this.newBlankNode()\n // alert(current.tagName+\": generated blank node, newSubject=\"+newSubject+\" currentObjectResource=\"+currentObjectResource)\n }\n if (relAtt && inlistAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n let list = listMapping[relAttPredicates[i]]\n if (!list) {\n list = []\n listMapping[predicate] = list\n }\n // console.log(\"Adding incomplete list for \"+predicate)\n incomplete.push({ predicate: relAttPredicates[i], list: list })\n }\n } else if (relAtt) {\n for (let i = 0; i < relAttPredicates.length; i++) {\n incomplete.push({ predicate: relAttPredicates[i], forward: true })\n }\n }\n if (revAtt) {\n for (let i = 0; i < revAttPredicates.length; i++) {\n incomplete.push({ predicate: revAttPredicates[i], forward: false })\n }\n }\n }\n // Step 11: Current property values\n if (propertyAtt) {\n var datatype = null\n var content = null\n if (datatypeAtt) {\n datatype = datatypeAtt.value === '' ? RDFaProcessor.PlainLiteralURI : this.parseTermOrCURIEOrAbsURI(datatypeAtt.value, vocabulary, context.terms, prefixes, base)\n if (datetimeAtt && !contentAtt) {\n content = datetimeAtt.value\n } else {\n content = datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI ? null : (contentAtt ? contentAtt.value : current.textContent)\n }\n } else if (contentAtt) {\n datatype = RDFaProcessor.PlainLiteralURI\n content = contentAtt.value\n } else if (datetimeAtt) {\n content = datetimeAtt.value\n datatype = RDFaProcessor.deriveDateTimeType(content)\n if (!datatype) {\n datatype = RDFaProcessor.PlainLiteralURI\n }\n } else if (!relAtt && !revAtt) {\n if (resourceAtt) {\n content = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base)\n }\n if (!content && hrefAtt) {\n content = this.resolveAndNormalize(base, encodeURI(hrefAtt.value))\n } else if (!content && srcAtt) {\n content = this.resolveAndNormalize(base, encodeURI(srcAtt.value))\n }\n if (content) {\n datatype = RDFaProcessor.objectURI\n }\n }\n if (!datatype) {\n if (typeofAtt && !aboutAtt) {\n datatype = RDFaProcessor.objectURI\n content = typedResource\n } else {\n content = current.textContent\n if (this.inHTMLMode && current.localName === 'time') {\n datatype = RDFaProcessor.deriveDateTimeType(content)\n }\n if (!datatype) {\n datatype = RDFaProcessor.PlainLiteralURI\n }\n }\n }\n values = this.tokenize(propertyAtt.value)\n for (let i = 0; i < values.length; i++) {\n let predicate = this.parsePredicate(values[i], vocabulary, context.terms, prefixes, base)\n if (predicate) {\n if (inlistAtt) {\n let list = listMapping[predicate]\n if (!list) {\n list = []\n listMapping[predicate] = list\n }\n list.push((datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI) ? { type: datatype, value: current.childNodes } : { type: datatype ? datatype : RDFaProcessor.PlainLiteralURI, value: content, language: language })\n } else {\n if (datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI) {\n this.addTriple(current, newSubject, predicate, { type: datatype, value: current.childNodes })\n } else {\n this.addTriple(current, newSubject, predicate, { type: datatype ? datatype : RDFaProcessor.PlainLiteralURI, value: content, language: language })\n // console.log(newSubject+\" \"+predicate+\"=\"+content)\n }\n }\n }\n }\n }\n // Sequence Step 12: complete incomplete triples with new subject\n if (newSubject && !skip) {\n for (let i = 0; i < context.incomplete.length; i++) {\n if (context.incomplete[i].list) {\n // console.log(\"Adding subject \"+newSubject+\" to list for \"+context.incomplete[i].predicate)\n // TODO: it is unclear what to do here\n context.incomplete[i].list.push({ type: RDFaProcessor.objectURI, value: newSubject })\n } else if (context.incomplete[i].forward) {\n // console.log(current.tagName+\": completing forward triple \"+context.incomplete[i].predicate+\" with object=\"+newSubject)\n this.addTriple(current, context.subject, context.incomplete[i].predicate, { type: RDFaProcessor.objectURI, value: newSubject })\n } else {\n // console.log(current.tagName+\": completing reverse triple with object=\"+context.subject)\n this.addTriple(current, newSubject, context.incomplete[i].predicate, { type: RDFaProcessor.objectURI, value: context.subject })\n }\n }\n }\n var childContext = null\n var listSubject = newSubject\n if (skip) {\n // TODO: should subject be null?\n childContext = this.push(context, context.subject)\n // TODO: should the entObject be passed along? If not, then intermediary children will keep properties from being associated with incomplete triples.\n // TODO: Verify: if the current baseURI has changed and the parentObject is the parent's base URI, then the baseURI should change\n childContext.parentObject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject\n childContext.incomplete = context.incomplete\n childContext.language = language\n childContext.prefixes = prefixes\n childContext.vocabulary = vocabulary\n } else {\n childContext = this.push(context, newSubject)\n childContext.parentObject = currentObjectResource ? currentObjectResource : (newSubject ? newSubject : context.subject)\n childContext.prefixes = prefixes\n childContext.incomplete = incomplete\n if (currentObjectResource) {\n // console.log(\"Generating new list mapping for \"+currentObjectResource)\n listSubject = currentObjectResource\n listMapping = {}\n listMappingDifferent = true\n }\n childContext.listMapping = listMapping\n childContext.language = language\n childContext.vocabulary = vocabulary\n }\n if (listMappingDifferent) {\n // console.log(\"Pushing list parent \"+current.localName)\n queue.unshift({ parent: current, context: context, subject: listSubject, listMapping: listMapping })\n }\n for (var child = current.lastChild; child; child = child.previousSibling) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n // console.log(\"Pushing child \"+child.localName)\n child.baseURI = current.baseURI\n queue.unshift({ current: child, context: childContext })\n }\n }\n }\n if (this.inHTMLMode) {\n this.copyProperties()\n }\n for (let i = 0; i < this.finishedHandlers.length; i++) {\n this.finishedHandlers[i](node)\n }\n }\n\n push (parent, subject) {\n return {\n parent: parent,\n subject: subject ? subject : (parent ? parent.subject : null),\n parentObject: null,\n incomplete: [],\n listMapping: parent ? parent.listMapping : {},\n language: parent ? parent.language : this.language,\n prefixes: parent ? parent.prefixes : this.target.graph.prefixes,\n terms: parent ? parent.terms : this.target.graph.terms,\n vocabulary: parent ? parent.vocabulary : this.vocabulary\n }\n }\n\n resolveAndNormalize (base, uri) {\n // console.log(\"Joining \" + uri + \" to \" + base + \" making \" + Uri.join(uri, base))\n return Uri.join(uri, base) // @@ normalize?\n }\n\n setContext (node) {\n // We only recognized XHTML+RDFa 1.1 if the version is set propertyly\n if (node.localName === 'html' && node.getAttribute('version') === 'XHTML+RDFa 1.1') {\n this.setXHTMLContext()\n } else if (node.localName === 'html' || node.namespaceURI === 'http://www.w3.org/1999/xhtml') {\n if (typeof document !== 'undefined' && document.doctype) {\n if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.0//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd') {\n console.log('WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode.')\n this.setHTMLContext()\n } 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') {\n this.setXHTMLContext()\n } else {\n this.setHTMLContext()\n }\n } else {\n this.setHTMLContext()\n }\n } else {\n this.setXMLContext()\n }\n }\n\n setHTMLContext () {\n this.setInitialContext()\n this.langAttributes = [\n {\n namespaceURI: 'http://www.w3.org/XML/1998/namespace',\n localName: 'lang'\n },\n { namespaceURI: null, localName: 'lang' }\n ]\n this.inXHTMLMode = false\n this.inHTMLMode = true\n }\n\n setInitialContext () {\n this.vocabulary = null\n // By default, the prefixes are terms are loaded to the RDFa 1.1. standard within the graph constructor\n this.langAttributes = [\n {\n namespaceURI: 'http://www.w3.org/XML/1998/namespace',\n localName: 'lang'\n }\n ]\n }\n\n setXHTMLContext () {\n this.setInitialContext()\n this.inXHTMLMode = true\n this.inHTMLMode = false\n this.langAttributes = [\n {\n namespaceURI: 'http://www.w3.org/XML/1998/namespace',\n localName: 'lang' },\n { namespaceURI: null, localName: 'lang' }\n ]\n // From http://www.w3.org/2011/rdfa-context/xhtml-rdfa-1.1\n this.target.graph.terms['alternate'] = 'http://www.w3.org/1999/xhtml/vocab#alternate'\n this.target.graph.terms['appendix'] = 'http://www.w3.org/1999/xhtml/vocab#appendix'\n this.target.graph.terms['bookmark'] = 'http://www.w3.org/1999/xhtml/vocab#bookmark'\n this.target.graph.terms['cite'] = 'http://www.w3.org/1999/xhtml/vocab#cite'\n this.target.graph.terms['chapter'] = 'http://www.w3.org/1999/xhtml/vocab#chapter'\n this.target.graph.terms['contents'] = 'http://www.w3.org/1999/xhtml/vocab#contents'\n this.target.graph.terms['copyright'] = 'http://www.w3.org/1999/xhtml/vocab#copyright'\n this.target.graph.terms['first'] = 'http://www.w3.org/1999/xhtml/vocab#first'\n this.target.graph.terms['glossary'] = 'http://www.w3.org/1999/xhtml/vocab#glossary'\n this.target.graph.terms['help'] = 'http://www.w3.org/1999/xhtml/vocab#help'\n this.target.graph.terms['icon'] = 'http://www.w3.org/1999/xhtml/vocab#icon'\n this.target.graph.terms['index'] = 'http://www.w3.org/1999/xhtml/vocab#index'\n this.target.graph.terms['last'] = 'http://www.w3.org/1999/xhtml/vocab#last'\n this.target.graph.terms['license'] = 'http://www.w3.org/1999/xhtml/vocab#license'\n this.target.graph.terms['meta'] = 'http://www.w3.org/1999/xhtml/vocab#meta'\n this.target.graph.terms['next'] = 'http://www.w3.org/1999/xhtml/vocab#next'\n this.target.graph.terms['prev'] = 'http://www.w3.org/1999/xhtml/vocab#prev'\n this.target.graph.terms['previous'] = 'http://www.w3.org/1999/xhtml/vocab#previous'\n this.target.graph.terms['section'] = 'http://www.w3.org/1999/xhtml/vocab#section'\n this.target.graph.terms['stylesheet'] = 'http://www.w3.org/1999/xhtml/vocab#stylesheet'\n this.target.graph.terms['subsection'] = 'http://www.w3.org/1999/xhtml/vocab#subsection'\n this.target.graph.terms['start'] = 'http://www.w3.org/1999/xhtml/vocab#start'\n this.target.graph.terms['top'] = 'http://www.w3.org/1999/xhtml/vocab#top'\n this.target.graph.terms['up'] = 'http://www.w3.org/1999/xhtml/vocab#up'\n this.target.graph.terms['p3pv1'] = 'http://www.w3.org/1999/xhtml/vocab#p3pv1'\n // other\n this.target.graph.terms['related'] = 'http://www.w3.org/1999/xhtml/vocab#related'\n this.target.graph.terms['role'] = 'http://www.w3.org/1999/xhtml/vocab#role'\n this.target.graph.terms['transformation'] = 'http://www.w3.org/1999/xhtml/vocab#transformation'\n }\n\n setXMLContext () {\n this.setInitialContext()\n this.inXHTMLMode = false\n this.inHTMLMode = false\n }\n\n tokenize (str) {\n return this.trim(str).split(/\\s+/)\n }\n\n toRDFNodeObject (x) {\n if (typeof x === 'undefined') return undefined\n if (typeof x === 'string') {\n if (x.substring(0, 2) === '_:') {\n if (typeof this.blankNodes[x.substring(2)] === 'undefined') {\n this.blankNodes[x.substring(2)] = new BlankNode(x.substring(2))\n }\n return this.blankNodes[x.substring(2)]\n }\n return rdf.namedNode(x)\n }\n switch (x.type) {\n case RDFaProcessor.objectURI:\n if (x.value.substring(0, 2) === '_:') {\n if (typeof this.blankNodes[x.value.substring(2)] === 'undefined') {\n this.blankNodes[x.value.substring(2)] = new BlankNode(x.value.substring(2))\n }\n return this.blankNodes[x.value.substring(2)]\n }\n return rdf.namedNode(x.value)\n case RDFaProcessor.PlainLiteralURI:\n return new Literal(x.value, x.language || '')\n case RDFaProcessor.XMLLiteralURI:\n case RDFaProcessor.HTMLLiteralURI:\n var string = ''\n Object.keys(x.value).forEach(function (i) {\n string += Util.domToString(x.value[i], this.htmlOptions)\n })\n return new Literal(string, '', new NamedNode(x.type))\n default:\n return new Literal(x.value, '', new NamedNode(x.type))\n }\n }\n\n trim (str) {\n return str.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '')\n }\n}\n\nRDFaProcessor.XMLLiteralURI =\n 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral'\nRDFaProcessor.HTMLLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML'\nRDFaProcessor.PlainLiteralURI =\n 'http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral'\nRDFaProcessor.objectURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'\nRDFaProcessor.typeURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'\nRDFaProcessor.nameChar =\n '[-A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u10000-\\uEFFFF\\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]'\nRDFaProcessor.nameStartChar =\n '[\\u0041-\\u005A\\u0061-\\u007A\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u00FF\\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_]'\nRDFaProcessor.NCNAME = new RegExp('^' + RDFaProcessor.nameStartChar +\n RDFaProcessor.nameChar + '*$')\n\n/*\nRDFaProcessor.prototype.resolveAndNormalize = function(base,href) {\n var u = base.resolve(href)\n var parsed = this.parseURI(u)\n parsed.normalize()\n return parsed.spec\n}\n*/\n\nRDFaProcessor.dateTimeTypes = [\n { pattern: /-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\\.[0-9]+)?S)?)?/,\n type: 'http://www.w3.org/2001/XMLSchema#duration' },\n { 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])?/,\n type: 'http://www.w3.org/2001/XMLSchema#dateTime' },\n { 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])?/,\n type: 'http://www.w3.org/2001/XMLSchema#date' },\n { 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])?/,\n type: 'http://www.w3.org/2001/XMLSchema#time' },\n { 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]/,\n type: 'http://www.w3.org/2001/XMLSchema#gYearMonth' },\n { pattern: /-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/,\n type: 'http://www.w3.org/2001/XMLSchema#gYear' }\n]\n\nmodule.exports = RDFaProcessor\n","/**\n * RDF/XML PARSER\n *\n * Parser believed to be in full positive RDF/XML parsing compliance\n * with the possible exception of handling deprecated RDF attributes\n * appropriately. Parser is believed to comply fully with other W3C\n * and industry standards where appropriate (DOM, ECMAScript, &c.)\n *\n * Author: David Sheets \n *\n * W3C® SOFTWARE NOTICE AND LICENSE\n * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231\n * This work (and included software, documentation such as READMEs, or\n * other related items) is being provided by the copyright holders under\n * the following license. By obtaining, using and/or copying this work,\n * you (the licensee) agree that you have read, understood, and will\n * comply with the following terms and conditions.\n *\n * Permission to copy, modify, and distribute this software and its\n * documentation, with or without modification, for any purpose and\n * without fee or royalty is hereby granted, provided that you include\n * the following on ALL copies of the software and documentation or\n * portions thereof, including modifications:\n *\n * 1. The full text of this NOTICE in a location viewable to users of\n * the redistributed or derivative work.\n * 2. Any pre-existing intellectual property disclaimers, notices, or terms and\n * conditions. If none exist, the W3C Software Short Notice should be\n * included (hypertext is preferred, text is permitted) within the body\n * of any redistributed or derivative code.\n * 3. Notice of any changes or modifications to the files, including the\n * date changes were made. (We recommend you provide URIs to the location\n * from which the code is derived.)\n *\n * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED \"AS IS,\" AND COPYRIGHT\n * HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS\n * FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR\n * DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,\n * TRADEMARKS OR OTHER RIGHTS.\n *\n * COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL\n * OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR\n * DOCUMENTATION.\n *\n * The name and trademarks of copyright holders may NOT be used in\n * advertising or publicity pertaining to the software without specific,\n * written prior permission. Title to copyright in this software and any\n * associated documentation will at all times remain with copyright\n * holders.\n */\n/**\n * @class RDFParser resource object tied to an RDFStore\n *\n * @author David Sheets \n *\n*/\n const uriUtil = require('./uri')\n\n/*\n * @constructor\n * @param {RDFStore} store An RDFStore object\n */\n\nvar RDFParser = function (store) {\n var RDFParser = {}\n\n /** Standard namespaces that we know how to handle @final\n * @member RDFParser\n */\n RDFParser.ns = {'RDF': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'RDFS': 'http://www.w3.org/2000/01/rdf-schema#'}\n\n /** DOM Level 2 node type magic numbers @final\n * @member RDFParser\n */\n RDFParser.nodeType = {'ELEMENT': 1, 'ATTRIBUTE': 2, 'TEXT': 3,\n 'CDATA_SECTION': 4, 'ENTITY_REFERENCE': 5,\n 'ENTITY': 6, 'PROCESSING_INSTRUCTION': 7,\n 'COMMENT': 8, 'DOCUMENT': 9, 'DOCUMENT_TYPE': 10,\n 'DOCUMENT_FRAGMENT': 11, 'NOTATION': 12}\n\n /**\n * Frame class for namespace and base URI lookups\n * Base lookups will always resolve because the parser knows\n * the default base.\n *\n * @private\n */\n\n this.frameFactory = function (parser, parent, element) {\n return {'NODE': 1, 'ARC': 2, 'parent': parent, 'parser': parser, 'store': parser.store, 'element': element,\n '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 */\n 'terminateFrame': function () {\n if (this.collection) {\n this.node.close()\n }\n }, /** Add a symbol of a certain type to the this frame */'addSymbol': function (type, uri) {\n uri = uriUtil.join(uri, this.base)\n this.node = this.store.sym(uri)\n\n this.nodeType = type\n }, /** Load any constructed triples into the store */'loadTriple': function () {\n if (this.parent.parent.collection) {\n this.parent.parent.node.append(this.node)\n } else {\n this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why)\n }\n if (this.parent.rdfid != null) {\n // reify\n var triple = this.store.sym(uriUtil.join('#' + this.parent.rdfid, this.base))\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(RDFParser.ns.RDF + 'Statement'), this.parser.why)\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'subject'), this.parent.parent.node, this.parser.why)\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'predicate'), this.parent.node, this.parser.why)\n\n this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'object'), this.node, this.parser.why)\n }\n }, /** Check if it's OK to load a triple */'isTripleToLoad': function () {\n return (this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType ===\n this.ARC && this.parent.parent.nodeType === this.NODE)\n }, /** Add a symbolic node to this frame */'addNode': function (uri) {\n this.addSymbol(this.NODE, uri)\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }, /** Add a collection node to this frame */'addCollection': function () {\n this.nodeType = this.NODE\n this.node = this.store.collection()\n this.collection = true\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }, /** Add a collection arc to this frame */'addCollectionArc': function () {\n this.nodeType = this.ARC\n }, /** Add a bnode to this frame */'addBNode': function (id) {\n if (id != null) {\n if (this.parser.bnodes[id] != null) {\n this.node = this.parser.bnodes[id]\n } else {\n this.node = this.parser.bnodes[id] = this.store.bnode()\n }\n } else {\n this.node = this.store.bnode()\n }\n this.nodeType = this.NODE\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }, /** Add an arc or property to this frame */'addArc': function (uri) {\n if (uri === RDFParser.ns.RDF + 'li') {\n uri = RDFParser.ns.RDF + '_' + this.parent.listIndex\n this.parent.listIndex++\n }\n\n this.addSymbol(this.ARC, uri)\n }, /** Add a literal to this frame */'addLiteral': function (value) {\n if (this.parent.datatype) {\n this.node = this.store.literal(value, '', this.store.sym(this.parent.datatype))\n } else {\n this.node = this.store.literal(value, this.lang)\n }\n this.nodeType = this.NODE\n if (this.isTripleToLoad()) {\n this.loadTriple()\n }\n }\n }\n }\n\n // from the OpenLayers source .. needed to get around IE problems.\n this.getAttributeNodeNS = function (node, uri, name) {\n var attributeNode = null\n if (node.getAttributeNodeNS) {\n attributeNode = node.getAttributeNodeNS(uri, name)\n } else {\n var attributes = node.attributes\n var potentialNode, fullName\n for (var i = 0;i < attributes.length; ++i) {\n potentialNode = attributes[i]\n if (potentialNode.namespaceURI === uri) {\n fullName = (potentialNode.prefix) ? (potentialNode.prefix + ':' + name) : name\n if (fullName === potentialNode.nodeName) {\n attributeNode = potentialNode\n break\n }\n }\n }\n }\n return attributeNode\n }\n\n /** Our triple store reference @private */\n\n this.store = store /** Our identified blank nodes @private */\n this.bnodes = {} /** A context for context-aware stores @private */\n this.why = null /** Reification flag */\n this.reify = false\n\n /**\n * Build our initial scope frame and parse the DOM into triples\n * @param {DOMTree} document The DOM to parse\n * @param {String} base The base URL to use\n * @param {Object} why The context to which this resource belongs\n */\n\n this.parse = function (document, base, why) {\n var children = document.childNodes // clean up for the next run\n this.cleanParser() // figure out the root element\n var root\n if (document.nodeType === RDFParser.nodeType.DOCUMENT) {\n for (var c = 0;c < children.length;c++) {\n if (children[c].nodeType === RDFParser.nodeType.ELEMENT) {\n root = children[c]\n break\n }\n }\n } else if (document.nodeType === RDFParser.nodeType.ELEMENT) {\n root = document\n } else {\n throw new Error(\"RDFParser: can't find root in \" + base + '. Halting. ')\n // return false\n }\n this.why = why // our topmost frame\n var f = this.frameFactory(this)\n this.base = base\n f.base = base\n f.lang = null // was '' but can't have langs like that 2015 (!)\n this.parseDOM(this.buildFrame(f, root))\n return true\n }\n\n this.parseDOM = function (frame) {\n // a DOM utility function used in parsing\n var rdfid\n var elementURI = function (el) {\n var result = ''\n if (el.namespaceURI == null) {\n throw new Error('RDF/XML syntax error: No namespace for ' + el.localName + ' in ' + this.base)\n }\n if (el.namespaceURI) {\n result = result + el.namespaceURI\n }\n if (el.localName) {\n result = result + el.localName\n } else if (el.nodeName) {\n if (el.nodeName.indexOf(':') >= 0)result = result + el.nodeName.split(':')[1]\n else result = result + el.nodeName\n }\n return result\n }.bind(this)\n var dig = true // if we'll dig down in the tree on the next iter\n while (frame.parent) {\n var dom = frame.element\n var attrs = dom.attributes\n if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION) {\n // we have a literal\n if (frame.parent.nodeType === frame.NODE) {\n // must have had attributes, store as rdf:value\n frame.addArc(RDFParser.ns.RDF + 'value')\n frame = this.buildFrame(frame)\n }\n frame.addLiteral(dom.nodeValue)\n } else if (elementURI(dom) !== RDFParser.ns.RDF + 'RDF') {\n // not root\n if (frame.parent && frame.parent.collection) {\n // we're a collection element\n frame.addCollectionArc()\n frame = this.buildFrame(frame, frame.element)\n frame.parent.element = null\n }\n if (!frame.parent || !frame.parent.nodeType || frame.parent.nodeType === frame.ARC) {\n // we need a node\n var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'about')\n rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID')\n if (about && rdfid) {\n throw new Error('RDFParser: ' + dom.nodeName + ' has both rdf:id and rdf:about.' +\n ' Halting. Only one of these' + ' properties may be specified on a' + ' node.')\n }\n if (!about && rdfid) {\n frame.addNode('#' + rdfid.nodeValue)\n dom.removeAttributeNode(rdfid)\n } else if (about == null && rdfid == null) {\n var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID')\n if (bnid) {\n frame.addBNode(bnid.nodeValue)\n dom.removeAttributeNode(bnid)\n } else {\n frame.addBNode()\n }\n } else {\n frame.addNode(about.nodeValue)\n dom.removeAttributeNode(about)\n }\n // Typed nodes\n var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'type')\n if (RDFParser.ns.RDF + 'Description' !== elementURI(dom)) {\n rdftype = {'nodeValue': elementURI(dom)}\n }\n if (rdftype != null) {\n this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(uriUtil.join(rdftype.nodeValue,\n frame.base)), this.why)\n if (rdftype.nodeName) {\n dom.removeAttributeNode(rdftype)\n }\n }\n // Property Attributes\n for (var x = attrs.length - 1; x >= 0; x--) {\n this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue,\n frame.lang), this.why)\n }\n } else {\n // we should add an arc (or implicit bnode+arc)\n frame.addArc(elementURI(dom)) // save the arc's rdf:ID if it has one\n if (this.reify) {\n rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID')\n if (rdfid) {\n frame.rdfid = rdfid.nodeValue\n dom.removeAttributeNode(rdfid)\n }\n }\n var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'parseType')\n var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'datatype')\n if (datatype) {\n frame.datatype = datatype.nodeValue\n dom.removeAttributeNode(datatype)\n }\n if (parsetype) {\n var nv = parsetype.nodeValue\n if (nv === 'Literal') {\n frame.datatype = RDFParser.ns.RDF + 'XMLLiteral'\n frame = this.buildFrame(frame)\n // Don't include the literal node, only its children\n frame.addLiteral(dom.childNodes)\n dig = false\n } else if (nv === 'Resource') {\n frame = this.buildFrame(frame, frame.element)\n frame.parent.element = null\n frame.addBNode()\n } else if (nv === 'Collection') {\n frame = this.buildFrame(frame, frame.element)\n frame.parent.element = null\n frame.addCollection()\n }\n dom.removeAttributeNode(parsetype)\n }\n if (attrs.length !== 0) {\n var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'resource')\n var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID')\n frame = this.buildFrame(frame)\n if (resource) {\n frame.addNode(resource.nodeValue)\n dom.removeAttributeNode(resource)\n } else {\n if (bnid2) {\n frame.addBNode(bnid2.nodeValue)\n dom.removeAttributeNode(bnid2)\n } else {\n frame.addBNode()\n }\n }\n for (var x1 = attrs.length - 1; x1 >= 0; x1--) {\n var f = this.buildFrame(frame)\n f.addArc(elementURI(attrs[x1]))\n if (elementURI(attrs[x1]) === RDFParser.ns.RDF + 'type') {\n (this.buildFrame(f)).addNode(attrs[x1].nodeValue)\n } else {\n (this.buildFrame(f)).addLiteral(attrs[x1].nodeValue)\n }\n }\n } else if (dom.childNodes.length === 0) {\n (this.buildFrame(frame)).addLiteral('')\n }\n }\n } // rdf:RDF\n // dig dug\n dom = frame.element\n while (frame.parent) {\n var pframe = frame\n while (dom == null) {\n frame = frame.parent\n dom = frame.element\n }\n var candidate = dom.childNodes && dom.childNodes[frame.lastChild]\n if (!candidate || !dig) {\n frame.terminateFrame()\n if (!(frame = frame.parent)) {\n break\n } // done\n dom = frame.element\n dig = true\n } else if ((candidate.nodeType !== RDFParser.nodeType.ELEMENT &&\n candidate.nodeType !== RDFParser.nodeType.TEXT &&\n candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION) ||\n ((candidate.nodeType === RDFParser.nodeType.TEXT ||\n candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) &&\n dom.childNodes.length !== 1)) {\n frame.lastChild++\n } else {\n // not a leaf\n frame.lastChild++\n frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1])\n break\n }\n }\n } // while\n }\n\n /**\n * Cleans out state from a previous parse run\n * @private\n */\n this.cleanParser = function () {\n this.bnodes = {}\n this.why = null\n }\n\n /**\n * Builds scope frame\n * @private\n */\n this.buildFrame = function (parent, element) {\n var frame = this.frameFactory(this, parent, element)\n if (parent) {\n frame.base = parent.base\n frame.lang = parent.lang\n }\n if (!element || element.nodeType === RDFParser.nodeType.TEXT ||\n element.nodeType === RDFParser.nodeType.CDATA_SECTION) {\n return frame\n }\n var attrs = element.attributes\n var base = element.getAttributeNode('xml:base')\n if (base != null) {\n frame.base = base.nodeValue\n element.removeAttribute('xml:base')\n }\n var lang = element.getAttributeNode('xml:lang')\n if (lang != null) {\n frame.lang = lang.nodeValue\n element.removeAttribute('xml:lang')\n }\n // remove all extraneous xml and xmlns attributes\n for (var x = attrs.length - 1;x >= 0;x--) {\n if (attrs[x].nodeName.substr(0, 3) === 'xml') {\n if (attrs[x].name.slice(0, 6) === 'xmlns:') {\n var uri = attrs[x].nodeValue // alert('base for namespac attr:'+this.base)\n if (this.base) uri = uriUtil.join(uri, this.base)\n this.store.setPrefixForURI(attrs[x].name.slice(6), uri)\n }\n //\t\talert('rdfparser: xml atribute: '+attrs[x].name) //@@\n element.removeAttributeNode(attrs[x])\n }\n }\n return frame\n }\n}\n\nmodule.exports = RDFParser\n","const NamedNode = require('./named-node')\n\nclass XSD {}\n\nXSD.boolean = new NamedNode('http://www.w3.org/2001/XMLSchema#boolean')\nXSD.dateTime = new NamedNode('http://www.w3.org/2001/XMLSchema#dateTime')\nXSD.decimal = new NamedNode('http://www.w3.org/2001/XMLSchema#decimal')\nXSD.double = new NamedNode('http://www.w3.org/2001/XMLSchema#double')\nXSD.integer = new NamedNode('http://www.w3.org/2001/XMLSchema#integer')\nXSD.langString =\n new NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString')\nXSD.string = new NamedNode('http://www.w3.org/2001/XMLSchema#string')\n\nmodule.exports = XSD\n","module.exports.convertToJson = convertToJson\nmodule.exports.convertToNQuads = convertToNQuads\n\nvar asyncLib = require('async') // @@ Goal: remove this dependency\nvar jsonld = require('jsonld')\nvar N3 = require('n3') // @@ Goal: remove this dependency\n\nfunction convertToJson (n3String, jsonCallback) {\n var jsonString\n var n3Parser = N3.Parser()\n var n3Writer = N3.Writer({\n format: 'N-Quads'\n })\n asyncLib.waterfall([\n function (callback) {\n n3Parser.parse(n3String, callback)\n },\n function (triple, prefix, callback) {\n if (triple !== null) {\n n3Writer.addTriple(triple)\n }\n if (typeof callback === 'function') {\n n3Writer.end(callback)\n }\n },\n function (result, callback) {\n try {\n jsonld.fromRDF(result, {\n format: 'application/nquads'\n }, callback)\n } catch (err) {\n callback(err)\n }\n },\n function (json, callback) {\n jsonString = JSON.stringify(json)\n jsonCallback(null, jsonString)\n }\n ], function (err, result) {\n jsonCallback(err, jsonString)\n }\n )\n}\n\nfunction convertToNQuads (n3String, nquadCallback) {\n var nquadString\n var n3Parser = N3.Parser()\n var n3Writer = N3.Writer({\n format: 'N-Quads'\n })\n asyncLib.waterfall([\n function (callback) {\n n3Parser.parse(n3String, callback)\n },\n function (triple, prefix, callback) {\n if (triple !== null) {\n n3Writer.addTriple(triple)\n }\n if (typeof callback === 'function') {\n n3Writer.end(callback)\n }\n },\n function (result, callback) {\n nquadString = result\n nquadCallback(null, nquadString)\n }\n ], function (err, result) {\n nquadCallback(err, nquadString)\n }\n )\n}\n","/**\n * A JavaScript implementation of the JSON-LD API.\n *\n * @author Dave Longley\n *\n * @license BSD 3-Clause License\n * Copyright (c) 2011-2015 Digital Bazaar, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the Digital Bazaar, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n(function() {\n\n// determine if in-browser or using node.js\nvar _nodejs = (\n typeof process !== 'undefined' && process.versions && process.versions.node);\nvar _browser = !_nodejs &&\n (typeof window !== 'undefined' || typeof self !== 'undefined');\nif(_browser) {\n if(typeof global === 'undefined') {\n if(typeof window !== 'undefined') {\n global = window;\n } else if(typeof self !== 'undefined') {\n global = self;\n } else if(typeof $ !== 'undefined') {\n global = $;\n }\n }\n}\n\n// attaches jsonld API to the given object\nvar wrapper = function(jsonld) {\n\n/* Core API */\n\n/**\n * Performs JSON-LD compaction.\n *\n * @param input the JSON-LD input to compact.\n * @param ctx the context to compact with.\n * @param [options] options to use:\n * [base] the base IRI to use.\n * [compactArrays] true to compact arrays to single values when\n * appropriate, false not to (default: true).\n * [graph] true to always output a top-level graph (default: false).\n * [expandContext] a context to expand with.\n * [skipExpansion] true to assume the input is expanded and skip\n * expansion, false not to, defaults to false.\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, compacted, ctx) called once the operation completes.\n */\njsonld.compact = function(input, ctx, options, callback) {\n if(arguments.length < 2) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not compact, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n if(ctx === null) {\n return jsonld.nextTick(function() {\n callback(new JsonLdError(\n 'The compaction context must not be null.',\n 'jsonld.CompactError', {code: 'invalid local context'}));\n });\n }\n\n // nothing to compact\n if(input === null) {\n return jsonld.nextTick(function() {\n callback(null, null);\n });\n }\n\n // set default options\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('compactArrays' in options)) {\n options.compactArrays = true;\n }\n if(!('graph' in options)) {\n options.graph = false;\n }\n if(!('skipExpansion' in options)) {\n options.skipExpansion = false;\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n if(!('link' in options)) {\n options.link = false;\n }\n if(options.link) {\n // force skip expansion when linking, \"link\" is not part of the public\n // API, it should only be called from framing\n options.skipExpansion = true;\n }\n\n var expand = function(input, options, callback) {\n if(options.skipExpansion) {\n return jsonld.nextTick(function() {\n callback(null, input);\n });\n }\n jsonld.expand(input, options, callback);\n };\n\n // expand input then do compaction\n expand(input, options, function(err, expanded) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand input before compaction.',\n 'jsonld.CompactError', {cause: err}));\n }\n\n // process context\n var activeCtx = _getInitialContext(options);\n jsonld.processContext(activeCtx, ctx, options, function(err, activeCtx) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not process context before compaction.',\n 'jsonld.CompactError', {cause: err}));\n }\n\n var compacted;\n try {\n // do compaction\n compacted = new Processor().compact(activeCtx, null, expanded, options);\n } catch(ex) {\n return callback(ex);\n }\n\n cleanup(null, compacted, activeCtx, options);\n });\n });\n\n // performs clean up after compaction\n function cleanup(err, compacted, activeCtx, options) {\n if(err) {\n return callback(err);\n }\n\n if(options.compactArrays && !options.graph && _isArray(compacted)) {\n if(compacted.length === 1) {\n // simplify to a single item\n compacted = compacted[0];\n } else if(compacted.length === 0) {\n // simplify to an empty object\n compacted = {};\n }\n } else if(options.graph && _isObject(compacted)) {\n // always use array if graph option is on\n compacted = [compacted];\n }\n\n // follow @context key\n if(_isObject(ctx) && '@context' in ctx) {\n ctx = ctx['@context'];\n }\n\n // build output context\n ctx = _clone(ctx);\n if(!_isArray(ctx)) {\n ctx = [ctx];\n }\n // remove empty contexts\n var tmp = ctx;\n ctx = [];\n for(var i = 0; i < tmp.length; ++i) {\n if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {\n ctx.push(tmp[i]);\n }\n }\n\n // remove array if only one context\n var hasContext = (ctx.length > 0);\n if(ctx.length === 1) {\n ctx = ctx[0];\n }\n\n // add context and/or @graph\n if(_isArray(compacted)) {\n // use '@graph' keyword\n var kwgraph = _compactIri(activeCtx, '@graph');\n var graph = compacted;\n compacted = {};\n if(hasContext) {\n compacted['@context'] = ctx;\n }\n compacted[kwgraph] = graph;\n } else if(_isObject(compacted) && hasContext) {\n // reorder keys so @context is first\n var graph = compacted;\n compacted = {'@context': ctx};\n for(var key in graph) {\n compacted[key] = graph[key];\n }\n }\n\n callback(null, compacted, activeCtx);\n }\n};\n\n/**\n * Performs JSON-LD expansion.\n *\n * @param input the JSON-LD input to expand.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [keepFreeFloatingNodes] true to keep free-floating nodes,\n * false not to, defaults to false.\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, expanded) called once the operation completes.\n */\njsonld.expand = function(input, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not expand, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n if(!('keepFreeFloatingNodes' in options)) {\n options.keepFreeFloatingNodes = false;\n }\n\n jsonld.nextTick(function() {\n // if input is a string, attempt to dereference remote document\n if(typeof input === 'string') {\n var done = function(err, remoteDoc) {\n if(err) {\n return callback(err);\n }\n try {\n if(!remoteDoc.document) {\n throw new JsonLdError(\n 'No remote document found at the given URL.',\n 'jsonld.NullRemoteDocument');\n }\n if(typeof remoteDoc.document === 'string') {\n remoteDoc.document = JSON.parse(remoteDoc.document);\n }\n } catch(ex) {\n return callback(new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL. URL ' +\n 'dereferencing not implemented.', 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n cause: ex,\n remoteDoc: remoteDoc\n }));\n }\n expand(remoteDoc);\n };\n var promise = options.documentLoader(input, done);\n if(promise && 'then' in promise) {\n promise.then(done.bind(null, null), done);\n }\n return;\n }\n // nothing to load\n expand({contextUrl: null, documentUrl: null, document: input});\n });\n\n function expand(remoteDoc) {\n // set default base\n if(!('base' in options)) {\n options.base = remoteDoc.documentUrl || '';\n }\n // build meta-object and retrieve all @context URLs\n var input = {\n document: _clone(remoteDoc.document),\n remoteContext: {'@context': remoteDoc.contextUrl}\n };\n if('expandContext' in options) {\n var expandContext = _clone(options.expandContext);\n if(typeof expandContext === 'object' && '@context' in expandContext) {\n input.expandContext = expandContext;\n } else {\n input.expandContext = {'@context': expandContext};\n }\n }\n _retrieveContextUrls(input, options, function(err, input) {\n if(err) {\n return callback(err);\n }\n\n var expanded;\n try {\n var processor = new Processor();\n var activeCtx = _getInitialContext(options);\n var document = input.document;\n var remoteContext = input.remoteContext['@context'];\n\n // process optional expandContext\n if(input.expandContext) {\n activeCtx = processor.processContext(\n activeCtx, input.expandContext['@context'], options);\n }\n\n // process remote context from HTTP Link Header\n if(remoteContext) {\n activeCtx = processor.processContext(\n activeCtx, remoteContext, options);\n }\n\n // expand document\n expanded = processor.expand(\n activeCtx, null, document, options, false);\n\n // optimize away @graph with no other properties\n if(_isObject(expanded) && ('@graph' in expanded) &&\n Object.keys(expanded).length === 1) {\n expanded = expanded['@graph'];\n } else if(expanded === null) {\n expanded = [];\n }\n\n // normalize to an array\n if(!_isArray(expanded)) {\n expanded = [expanded];\n }\n } catch(ex) {\n return callback(ex);\n }\n callback(null, expanded);\n });\n }\n};\n\n/**\n * Performs JSON-LD flattening.\n *\n * @param input the JSON-LD to flatten.\n * @param ctx the context to use to compact the flattened output, or null.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, flattened) called once the operation completes.\n */\njsonld.flatten = function(input, ctx, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not flatten, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n } else if(typeof ctx === 'function') {\n callback = ctx;\n ctx = null;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n\n // expand input\n jsonld.expand(input, options, function(err, _input) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand input before flattening.',\n 'jsonld.FlattenError', {cause: err}));\n }\n\n var flattened;\n try {\n // do flattening\n flattened = new Processor().flatten(_input);\n } catch(ex) {\n return callback(ex);\n }\n\n if(ctx === null) {\n return callback(null, flattened);\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n jsonld.compact(flattened, ctx, options, function(err, compacted) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not compact flattened output.',\n 'jsonld.FlattenError', {cause: err}));\n }\n callback(null, compacted);\n });\n });\n};\n\n/**\n * Performs JSON-LD framing.\n *\n * @param input the JSON-LD input to frame.\n * @param frame the JSON-LD frame to use.\n * @param [options] the framing options.\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [embed] default @embed flag: '@last', '@always', '@never', '@link'\n * (default: '@last').\n * [explicit] default @explicit flag (default: false).\n * [requireAll] default @requireAll flag (default: true).\n * [omitDefault] default @omitDefault flag (default: false).\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, framed) called once the operation completes.\n */\njsonld.frame = function(input, frame, options, callback) {\n if(arguments.length < 2) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not frame, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n if(!('embed' in options)) {\n options.embed = '@last';\n }\n options.explicit = options.explicit || false;\n if(!('requireAll' in options)) {\n options.requireAll = true;\n }\n options.omitDefault = options.omitDefault || false;\n\n jsonld.nextTick(function() {\n // if frame is a string, attempt to dereference remote document\n if(typeof frame === 'string') {\n var done = function(err, remoteDoc) {\n if(err) {\n return callback(err);\n }\n try {\n if(!remoteDoc.document) {\n throw new JsonLdError(\n 'No remote document found at the given URL.',\n 'jsonld.NullRemoteDocument');\n }\n if(typeof remoteDoc.document === 'string') {\n remoteDoc.document = JSON.parse(remoteDoc.document);\n }\n } catch(ex) {\n return callback(new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL. URL ' +\n 'dereferencing not implemented.', 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n cause: ex,\n remoteDoc: remoteDoc\n }));\n }\n doFrame(remoteDoc);\n };\n var promise = options.documentLoader(frame, done);\n if(promise && 'then' in promise) {\n promise.then(done.bind(null, null), done);\n }\n return;\n }\n // nothing to load\n doFrame({contextUrl: null, documentUrl: null, document: frame});\n });\n\n function doFrame(remoteFrame) {\n // preserve frame context and add any Link header context\n var frame = remoteFrame.document;\n var ctx;\n if(frame) {\n ctx = frame['@context'];\n if(remoteFrame.contextUrl) {\n if(!ctx) {\n ctx = remoteFrame.contextUrl;\n } else if(_isArray(ctx)) {\n ctx.push(remoteFrame.contextUrl);\n } else {\n ctx = [ctx, remoteFrame.contextUrl];\n }\n frame['@context'] = ctx;\n } else {\n ctx = ctx || {};\n }\n } else {\n ctx = {};\n }\n\n // expand input\n jsonld.expand(input, options, function(err, expanded) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand input before framing.',\n 'jsonld.FrameError', {cause: err}));\n }\n\n // expand frame\n var opts = _clone(options);\n opts.isFrame = true;\n opts.keepFreeFloatingNodes = true;\n jsonld.expand(frame, opts, function(err, expandedFrame) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand frame before framing.',\n 'jsonld.FrameError', {cause: err}));\n }\n\n var framed;\n try {\n // do framing\n framed = new Processor().frame(expanded, expandedFrame, opts);\n } catch(ex) {\n return callback(ex);\n }\n\n // compact result (force @graph option to true, skip expansion,\n // check for linked embeds)\n opts.graph = true;\n opts.skipExpansion = true;\n opts.link = {};\n jsonld.compact(framed, ctx, opts, function(err, compacted, ctx) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not compact framed output.',\n 'jsonld.FrameError', {cause: err}));\n }\n // get graph alias\n var graph = _compactIri(ctx, '@graph');\n // remove @preserve from results\n opts.link = {};\n compacted[graph] = _removePreserve(ctx, compacted[graph], opts);\n callback(null, compacted);\n });\n });\n });\n }\n};\n\n/**\n * **Experimental**\n *\n * Links a JSON-LD document's nodes in memory.\n *\n * @param input the JSON-LD document to link.\n * @param ctx the JSON-LD context to apply.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, linked) called once the operation completes.\n */\njsonld.link = function(input, ctx, options, callback) {\n // API matches running frame with a wildcard frame and embed: '@link'\n // get arguments\n var frame = {};\n if(ctx) {\n frame['@context'] = ctx;\n }\n frame['@embed'] = '@link';\n jsonld.frame(input, frame, options, callback);\n};\n\n/**\n * **Deprecated**\n *\n * Performs JSON-LD objectification.\n *\n * @param input the JSON-LD document to objectify.\n * @param ctx the JSON-LD context to apply.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, linked) called once the operation completes.\n */\njsonld.objectify = function(input, ctx, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n\n // expand input\n jsonld.expand(input, options, function(err, _input) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand input before linking.',\n 'jsonld.LinkError', {cause: err}));\n }\n\n var flattened;\n try {\n // flatten the graph\n flattened = new Processor().flatten(_input);\n } catch(ex) {\n return callback(ex);\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n jsonld.compact(flattened, ctx, options, function(err, compacted, ctx) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not compact flattened output before linking.',\n 'jsonld.LinkError', {cause: err}));\n }\n // get graph alias\n var graph = _compactIri(ctx, '@graph');\n var top = compacted[graph][0];\n\n var recurse = function(subject) {\n // can't replace just a string\n if(!_isObject(subject) && !_isArray(subject)) {\n return;\n }\n\n // bottom out recursion on re-visit\n if(_isObject(subject)) {\n if(recurse.visited[subject['@id']]) {\n return;\n }\n recurse.visited[subject['@id']] = true;\n }\n\n // each array element *or* object key\n for(var k in subject) {\n var obj = subject[k];\n var isid = (jsonld.getContextValue(ctx, k, '@type') === '@id');\n\n // can't replace a non-object or non-array unless it's an @id\n if(!_isArray(obj) && !_isObject(obj) && !isid) {\n continue;\n }\n\n if(_isString(obj) && isid) {\n subject[k] = obj = top[obj];\n recurse(obj);\n } else if(_isArray(obj)) {\n for(var i = 0; i < obj.length; ++i) {\n if(_isString(obj[i]) && isid) {\n obj[i] = top[obj[i]];\n } else if(_isObject(obj[i]) && '@id' in obj[i]) {\n obj[i] = top[obj[i]['@id']];\n }\n recurse(obj[i]);\n }\n } else if(_isObject(obj)) {\n var sid = obj['@id'];\n subject[k] = obj = top[sid];\n recurse(obj);\n }\n }\n };\n recurse.visited = {};\n recurse(top);\n\n compacted.of_type = {};\n for(var s in top) {\n if(!('@type' in top[s])) {\n continue;\n }\n var types = top[s]['@type'];\n if(!_isArray(types)) {\n types = [types];\n }\n for(var t = 0; t < types.length; ++t) {\n if(!(types[t] in compacted.of_type)) {\n compacted.of_type[types[t]] = [];\n }\n compacted.of_type[types[t]].push(top[s]);\n }\n }\n callback(null, compacted);\n });\n });\n};\n\n/**\n * Performs RDF dataset normalization on the given input. The input is JSON-LD\n * unless the 'inputFormat' option is used. The output is an RDF dataset\n * unless the 'format' option is used.\n *\n * @param input the input to normalize as JSON-LD or as a format specified by\n * the 'inputFormat' option.\n * @param [options] the options to use:\n * [algorithm] the normalization algorithm to use, `URDNA2015` or\n * `URGNA2012` (default: `URGNA2012`).\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [inputFormat] the format if input is not JSON-LD:\n * 'application/nquads' for N-Quads.\n * [format] the format if output is a string:\n * 'application/nquads' for N-Quads.\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, normalized) called once the operation completes.\n */\njsonld.normalize = function(input, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not normalize, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('algorithm' in options)) {\n options.algorithm = 'URGNA2012';\n }\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n\n if('inputFormat' in options) {\n if(options.inputFormat !== 'application/nquads') {\n return callback(new JsonLdError(\n 'Unknown normalization input format.',\n 'jsonld.NormalizeError'));\n }\n var parsedInput = _parseNQuads(input);\n // do normalization\n new Processor().normalize(parsedInput, options, callback);\n } else {\n // convert to RDF dataset then do normalization\n var opts = _clone(options);\n delete opts.format;\n opts.produceGeneralizedRdf = false;\n jsonld.toRDF(input, opts, function(err, dataset) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not convert input to RDF dataset before normalization.',\n 'jsonld.NormalizeError', {cause: err}));\n }\n // do normalization\n new Processor().normalize(dataset, options, callback);\n });\n }\n};\n\n/**\n * Converts an RDF dataset to JSON-LD.\n *\n * @param dataset a serialized string of RDF in a format specified by the\n * format option or an RDF dataset to convert.\n * @param [options] the options to use:\n * [format] the format if dataset param must first be parsed:\n * 'application/nquads' for N-Quads (default).\n * [rdfParser] a custom RDF-parser to use to parse the dataset.\n * [useRdfType] true to use rdf:type, false to use @type\n * (default: false).\n * [useNativeTypes] true to convert XSD types into native types\n * (boolean, integer, double), false not to (default: false).\n * @param callback(err, output) called once the operation completes.\n */\njsonld.fromRDF = function(dataset, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not convert from RDF, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('useRdfType' in options)) {\n options.useRdfType = false;\n }\n if(!('useNativeTypes' in options)) {\n options.useNativeTypes = false;\n }\n\n if(!('format' in options) && _isString(dataset)) {\n // set default format to nquads\n if(!('format' in options)) {\n options.format = 'application/nquads';\n }\n }\n\n jsonld.nextTick(function() {\n // handle special format\n var rdfParser;\n if(options.format) {\n // check supported formats\n rdfParser = options.rdfParser || _rdfParsers[options.format];\n if(!rdfParser) {\n return callback(new JsonLdError(\n 'Unknown input format.',\n 'jsonld.UnknownFormat', {format: options.format}));\n }\n } else {\n // no-op parser, assume dataset already parsed\n rdfParser = function() {\n return dataset;\n };\n }\n\n var callbackCalled = false;\n try {\n // rdf parser may be async or sync, always pass callback\n dataset = rdfParser(dataset, function(err, dataset) {\n callbackCalled = true;\n if(err) {\n return callback(err);\n }\n fromRDF(dataset, options, callback);\n });\n } catch(e) {\n if(!callbackCalled) {\n return callback(e);\n }\n throw e;\n }\n // handle synchronous or promise-based parser\n if(dataset) {\n // if dataset is actually a promise\n if('then' in dataset) {\n return dataset.then(function(dataset) {\n fromRDF(dataset, options, callback);\n }, callback);\n }\n // parser is synchronous\n fromRDF(dataset, options, callback);\n }\n\n function fromRDF(dataset, options, callback) {\n // convert from RDF\n new Processor().fromRDF(dataset, options, callback);\n }\n });\n};\n\n/**\n * Outputs the RDF dataset found in the given JSON-LD object.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [format] the format to use to output a string:\n * 'application/nquads' for N-Quads.\n * [produceGeneralizedRdf] true to output generalized RDF, false\n * to produce only standard RDF (default: false).\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, dataset) called once the operation completes.\n */\njsonld.toRDF = function(input, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not convert to RDF, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n\n // expand input\n jsonld.expand(input, options, function(err, expanded) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand input before serialization to RDF.',\n 'jsonld.RdfError', {cause: err}));\n }\n\n var dataset;\n try {\n // output RDF dataset\n dataset = Processor.prototype.toRDF(expanded, options);\n if(options.format) {\n if(options.format === 'application/nquads') {\n return callback(null, _toNQuads(dataset));\n }\n throw new JsonLdError(\n 'Unknown output format.',\n 'jsonld.UnknownFormat', {format: options.format});\n }\n } catch(ex) {\n return callback(ex);\n }\n callback(null, dataset);\n });\n};\n\n/**\n * **Experimental**\n *\n * Recursively flattens the nodes in the given JSON-LD input into a map of\n * node ID => node.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [namer] (deprecated)\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, nodeMap) called once the operation completes.\n */\njsonld.createNodeMap = function(input, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not create node map, too few arguments.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n\n // set default options\n if(!('base' in options)) {\n options.base = (typeof input === 'string') ? input : '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n\n // expand input\n jsonld.expand(input, options, function(err, _input) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not expand input before creating node map.',\n 'jsonld.CreateNodeMapError', {cause: err}));\n }\n\n var nodeMap;\n try {\n nodeMap = new Processor().createNodeMap(_input, options);\n } catch(ex) {\n return callback(ex);\n }\n\n callback(null, nodeMap);\n });\n};\n\n/**\n * **Experimental**\n *\n * Merges two or more JSON-LD documents into a single flattened document.\n *\n * @param docs the JSON-LD documents to merge together.\n * @param ctx the context to use to compact the merged result, or null.\n * @param [options] the options to use:\n * [base] the base IRI to use.\n * [expandContext] a context to expand with.\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [namer] (deprecated).\n * [mergeNodes] true to merge properties for nodes with the same ID,\n * false to ignore new properties for nodes with the same ID once\n * the ID has been defined; note that this may not prevent merging\n * new properties where a node is in the `object` position\n * (default: true).\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, merged) called once the operation completes.\n */\njsonld.merge = function(docs, ctx, options, callback) {\n if(arguments.length < 1) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not merge, too few arguments.'));\n });\n }\n if(!_isArray(docs)) {\n return jsonld.nextTick(function() {\n callback(new TypeError('Could not merge, \"docs\" must be an array.'));\n });\n }\n\n // get arguments\n if(typeof options === 'function') {\n callback = options;\n options = {};\n } else if(typeof ctx === 'function') {\n callback = ctx;\n ctx = null;\n options = {};\n }\n options = options || {};\n\n // expand all documents\n var expanded = [];\n var error = null;\n var count = docs.length;\n for(var i = 0; i < docs.length; ++i) {\n var opts = {};\n for(var key in options) {\n opts[key] = options[key];\n }\n jsonld.expand(docs[i], opts, expandComplete);\n }\n\n function expandComplete(err, _input) {\n if(error) {\n return;\n }\n if(err) {\n error = err;\n return callback(new JsonLdError(\n 'Could not expand input before flattening.',\n 'jsonld.FlattenError', {cause: err}));\n }\n expanded.push(_input);\n if(--count === 0) {\n merge(expanded);\n }\n }\n\n function merge(expanded) {\n var mergeNodes = true;\n if('mergeNodes' in options) {\n mergeNodes = options.mergeNodes;\n }\n\n var issuer = options.namer || options.issuer || new IdentifierIssuer('_:b');\n var graphs = {'@default': {}};\n\n var defaultGraph;\n try {\n for(var i = 0; i < expanded.length; ++i) {\n // uniquely relabel blank nodes\n var doc = expanded[i];\n doc = jsonld.relabelBlankNodes(doc, {\n issuer: new IdentifierIssuer('_:b' + i + '-')\n });\n\n // add nodes to the shared node map graphs if merging nodes, to a\n // separate graph set if not\n var _graphs = (mergeNodes || i === 0) ? graphs : {'@default': {}};\n _createNodeMap(doc, _graphs, '@default', issuer);\n\n if(_graphs !== graphs) {\n // merge document graphs but don't merge existing nodes\n for(var graphName in _graphs) {\n var _nodeMap = _graphs[graphName];\n if(!(graphName in graphs)) {\n graphs[graphName] = _nodeMap;\n continue;\n }\n var nodeMap = graphs[graphName];\n for(var key in _nodeMap) {\n if(!(key in nodeMap)) {\n nodeMap[key] = _nodeMap[key];\n }\n }\n }\n }\n }\n\n // add all non-default graphs to default graph\n defaultGraph = _mergeNodeMaps(graphs);\n } catch(ex) {\n return callback(ex);\n }\n\n // produce flattened output\n var flattened = [];\n var keys = Object.keys(defaultGraph).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var node = defaultGraph[keys[ki]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n flattened.push(node);\n }\n }\n\n if(ctx === null) {\n return callback(null, flattened);\n }\n\n // compact result (force @graph option to true, skip expansion)\n options.graph = true;\n options.skipExpansion = true;\n jsonld.compact(flattened, ctx, options, function(err, compacted) {\n if(err) {\n return callback(new JsonLdError(\n 'Could not compact merged output.',\n 'jsonld.MergeError', {cause: err}));\n }\n callback(null, compacted);\n });\n }\n};\n\n/**\n * Relabels all blank nodes in the given JSON-LD input.\n *\n * @param input the JSON-LD input.\n * @param [options] the options to use:\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [namer] (deprecated).\n */\njsonld.relabelBlankNodes = function(input, options) {\n options = options || {};\n var issuer = options.namer || options.issuer || new IdentifierIssuer('_:b');\n return _labelBlankNodes(issuer, input);\n};\n\n/**\n * Prepends a base IRI to the given relative IRI.\n *\n * @param base the base IRI.\n * @param iri the relative IRI.\n *\n * @return the absolute IRI.\n */\njsonld.prependBase = function(base, iri) {\n return _prependBase(base, iri);\n};\n\n/**\n * The default document loader for external documents. If the environment\n * is node.js, a callback-continuation-style document loader is used; otherwise,\n * a promises-style document loader is used.\n *\n * @param url the URL to load.\n * @param callback(err, remoteDoc) called once the operation completes,\n * if using a non-promises API.\n *\n * @return a promise, if using a promises API.\n */\njsonld.documentLoader = function(url, callback) {\n var err = new JsonLdError(\n 'Could not retrieve a JSON-LD document from the URL. URL ' +\n 'dereferencing not implemented.', 'jsonld.LoadDocumentError',\n {code: 'loading document failed'});\n if(_nodejs) {\n return callback(err, {contextUrl: null, documentUrl: url, document: null});\n }\n return jsonld.promisify(function(callback) {\n callback(err);\n });\n};\n\n/**\n * Deprecated default document loader. Use or override jsonld.documentLoader\n * instead.\n */\njsonld.loadDocument = function(url, callback) {\n var promise = jsonld.documentLoader(url, callback);\n if(promise && 'then' in promise) {\n promise.then(callback.bind(null, null), callback);\n }\n};\n\n/* Promises API */\n\n/**\n * Creates a new promises API object.\n *\n * @param [options] the options to use:\n * [api] an object to attach the API to.\n * [version] 'json-ld-1.0' to output a standard JSON-LD 1.0 promises\n * API, 'jsonld.js' to output the same with augmented proprietary\n * methods (default: 'jsonld.js')\n *\n * @return the promises API object.\n */\njsonld.promises = function(options) {\n options = options || {};\n var slice = Array.prototype.slice;\n var promisify = jsonld.promisify;\n\n // handle 'api' option as version, set defaults\n var api = options.api || {};\n var version = options.version || 'jsonld.js';\n if(typeof options.api === 'string') {\n if(!options.version) {\n version = options.api;\n }\n api = {};\n }\n\n // The Web IDL test harness will check the number of parameters defined in\n // the functions below. The number of parameters must exactly match the\n // required (non-optional) parameters of the JsonLdProcessor interface as\n // defined here:\n // https://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface\n\n api.expand = function(input) {\n if(arguments.length < 1) {\n throw new TypeError('Could not expand, too few arguments.');\n }\n return promisify.apply(null, [jsonld.expand].concat(slice.call(arguments)));\n };\n api.compact = function(input, ctx) {\n if(arguments.length < 2) {\n throw new TypeError('Could not compact, too few arguments.');\n }\n var compact = function(input, ctx, options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n // ensure only one value is returned in callback\n jsonld.compact(input, ctx, options, function(err, compacted) {\n callback(err, compacted);\n });\n };\n return promisify.apply(null, [compact].concat(slice.call(arguments)));\n };\n api.flatten = function(input) {\n if(arguments.length < 1) {\n throw new TypeError('Could not flatten, too few arguments.');\n }\n return promisify.apply(\n null, [jsonld.flatten].concat(slice.call(arguments)));\n };\n api.frame = function(input, frame) {\n if(arguments.length < 2) {\n throw new TypeError('Could not frame, too few arguments.');\n }\n return promisify.apply(null, [jsonld.frame].concat(slice.call(arguments)));\n };\n api.fromRDF = function(dataset) {\n if(arguments.length < 1) {\n throw new TypeError('Could not convert from RDF, too few arguments.');\n }\n return promisify.apply(\n null, [jsonld.fromRDF].concat(slice.call(arguments)));\n };\n api.toRDF = function(input) {\n if(arguments.length < 1) {\n throw new TypeError('Could not convert to RDF, too few arguments.');\n }\n return promisify.apply(null, [jsonld.toRDF].concat(slice.call(arguments)));\n };\n api.normalize = function(input) {\n if(arguments.length < 1) {\n throw new TypeError('Could not normalize, too few arguments.');\n }\n return promisify.apply(\n null, [jsonld.normalize].concat(slice.call(arguments)));\n };\n\n if(version === 'jsonld.js') {\n api.link = function(input, ctx) {\n if(arguments.length < 2) {\n throw new TypeError('Could not link, too few arguments.');\n }\n return promisify.apply(\n null, [jsonld.link].concat(slice.call(arguments)));\n };\n api.objectify = function(input) {\n return promisify.apply(\n null, [jsonld.objectify].concat(slice.call(arguments)));\n };\n api.createNodeMap = function(input) {\n return promisify.apply(\n null, [jsonld.createNodeMap].concat(slice.call(arguments)));\n };\n api.merge = function(input) {\n return promisify.apply(\n null, [jsonld.merge].concat(slice.call(arguments)));\n };\n }\n\n try {\n jsonld.Promise = global.Promise || require('es6-promise').Promise;\n } catch(e) {\n var f = function() {\n throw new Error('Unable to find a Promise implementation.');\n };\n for(var method in api) {\n api[method] = f;\n }\n }\n\n return api;\n};\n\n/**\n * Converts a node.js async op into a promise w/boxed resolved value(s).\n *\n * @param op the operation to convert.\n *\n * @return the promise.\n */\njsonld.promisify = function(op) {\n if(!jsonld.Promise) {\n try {\n jsonld.Promise = global.Promise || require('es6-promise').Promise;\n } catch(e) {\n throw new Error('Unable to find a Promise implementation.');\n }\n }\n var args = Array.prototype.slice.call(arguments, 1);\n return new jsonld.Promise(function(resolve, reject) {\n op.apply(null, args.concat(function(err, value) {\n if(!err) {\n resolve(value);\n } else {\n reject(err);\n }\n }));\n });\n};\n\n// extend jsonld.promises w/jsonld.js methods\njsonld.promises({api: jsonld.promises});\n\n/* WebIDL API */\n\nfunction JsonLdProcessor() {}\nJsonLdProcessor.prototype = jsonld.promises({version: 'json-ld-1.0'});\nJsonLdProcessor.prototype.toString = function() {\n if(this instanceof JsonLdProcessor) {\n return '[object JsonLdProcessor]';\n }\n return '[object JsonLdProcessorPrototype]';\n};\njsonld.JsonLdProcessor = JsonLdProcessor;\n\n// IE8 has Object.defineProperty but it only\n// works on DOM nodes -- so feature detection\n// requires try/catch :-(\nvar canDefineProperty = !!Object.defineProperty;\nif(canDefineProperty) {\n try {\n Object.defineProperty({}, 'x', {});\n } catch(e) {\n canDefineProperty = false;\n }\n}\n\nif(canDefineProperty) {\n Object.defineProperty(JsonLdProcessor, 'prototype', {\n writable: false,\n enumerable: false\n });\n Object.defineProperty(JsonLdProcessor.prototype, 'constructor', {\n writable: true,\n enumerable: false,\n configurable: true,\n value: JsonLdProcessor\n });\n}\n\n// setup browser global JsonLdProcessor\nif(_browser && typeof global.JsonLdProcessor === 'undefined') {\n if(canDefineProperty) {\n Object.defineProperty(global, 'JsonLdProcessor', {\n writable: true,\n enumerable: false,\n configurable: true,\n value: JsonLdProcessor\n });\n } else {\n global.JsonLdProcessor = JsonLdProcessor;\n }\n}\n\n/* Utility API */\n\n// define setImmediate and nextTick\n//// nextTick implementation with browser-compatible fallback ////\n// from https://github.com/caolan/async/blob/master/lib/async.js\n\n// capture the global reference to guard against fakeTimer mocks\nvar _setImmediate = typeof setImmediate === 'function' && setImmediate;\n\nvar _delay = _setImmediate ? function(fn) {\n // not a direct alias (for IE10 compatibility)\n _setImmediate(fn);\n} : function(fn) {\n setTimeout(fn, 0);\n};\n\nif(typeof process === 'object' && typeof process.nextTick === 'function') {\n jsonld.nextTick = process.nextTick;\n} else {\n jsonld.nextTick = _delay;\n}\njsonld.setImmediate = _setImmediate ? _delay : jsonld.nextTick;\n\n/**\n * Parses a link header. The results will be key'd by the value of \"rel\".\n *\n * Link: ; rel=\"http://www.w3.org/ns/json-ld#context\"; type=\"application/ld+json\"\n *\n * Parses as: {\n * 'http://www.w3.org/ns/json-ld#context': {\n * target: http://json-ld.org/contexts/person.jsonld,\n * type: 'application/ld+json'\n * }\n * }\n *\n * If there is more than one \"rel\" with the same IRI, then entries in the\n * resulting map for that \"rel\" will be arrays.\n *\n * @param header the link header to parse.\n */\njsonld.parseLinkHeader = function(header) {\n var rval = {};\n // split on unbracketed/unquoted commas\n var entries = header.match(/(?:<[^>]*?>|\"[^\"]*?\"|[^,])+/g);\n var rLinkHeader = /\\s*<([^>]*?)>\\s*(?:;\\s*(.*))?/;\n for(var i = 0; i < entries.length; ++i) {\n var match = entries[i].match(rLinkHeader);\n if(!match) {\n continue;\n }\n var result = {target: match[1]};\n var params = match[2];\n var rParams = /(.*?)=(?:(?:\"([^\"]*?)\")|([^\"]*?))\\s*(?:(?:;\\s*)|$)/g;\n while(match = rParams.exec(params)) {\n result[match[1]] = (match[2] === undefined) ? match[3] : match[2];\n }\n var rel = result['rel'] || '';\n if(_isArray(rval[rel])) {\n rval[rel].push(result);\n } else if(rel in rval) {\n rval[rel] = [rval[rel], result];\n } else {\n rval[rel] = result;\n }\n }\n return rval;\n};\n\n/**\n * Creates a simple queue for requesting documents.\n */\njsonld.RequestQueue = function() {\n this._requests = {};\n};\njsonld.RequestQueue.prototype.wrapLoader = function(loader) {\n this._loader = loader;\n this._usePromise = (loader.length === 1);\n return this.add.bind(this);\n};\njsonld.RequestQueue.prototype.add = function(url, callback) {\n var self = this;\n\n // callback must be given if not using promises\n if(!callback && !self._usePromise) {\n throw new Error('callback must be specified.');\n }\n\n // Promise-based API\n if(self._usePromise) {\n return new jsonld.Promise(function(resolve, reject) {\n var load = self._requests[url];\n if(!load) {\n // load URL then remove from queue\n load = self._requests[url] = self._loader(url)\n .then(function(remoteDoc) {\n delete self._requests[url];\n return remoteDoc;\n }).catch(function(err) {\n delete self._requests[url];\n throw err;\n });\n }\n // resolve/reject promise once URL has been loaded\n load.then(function(remoteDoc) {\n resolve(remoteDoc);\n }).catch(function(err) {\n reject(err);\n });\n });\n }\n\n // callback-based API\n if(url in self._requests) {\n self._requests[url].push(callback);\n } else {\n self._requests[url] = [callback];\n self._loader(url, function(err, remoteDoc) {\n var callbacks = self._requests[url];\n delete self._requests[url];\n for(var i = 0; i < callbacks.length; ++i) {\n callbacks[i](err, remoteDoc);\n }\n });\n }\n};\n\n/**\n * Creates a simple document cache that retains documents for a short\n * period of time.\n *\n * FIXME: Implement simple HTTP caching instead.\n *\n * @param size the maximum size of the cache.\n */\njsonld.DocumentCache = function(size) {\n this.order = [];\n this.cache = {};\n this.size = size || 50;\n this.expires = 30 * 1000;\n};\njsonld.DocumentCache.prototype.get = function(url) {\n if(url in this.cache) {\n var entry = this.cache[url];\n if(entry.expires >= +new Date()) {\n return entry.ctx;\n }\n delete this.cache[url];\n this.order.splice(this.order.indexOf(url), 1);\n }\n return null;\n};\njsonld.DocumentCache.prototype.set = function(url, ctx) {\n if(this.order.length === this.size) {\n delete this.cache[this.order.shift()];\n }\n this.order.push(url);\n this.cache[url] = {ctx: ctx, expires: (+new Date() + this.expires)};\n};\n\n/**\n * Creates an active context cache.\n *\n * @param size the maximum size of the cache.\n */\njsonld.ActiveContextCache = function(size) {\n this.order = [];\n this.cache = {};\n this.size = size || 100;\n};\njsonld.ActiveContextCache.prototype.get = function(activeCtx, localCtx) {\n var key1 = JSON.stringify(activeCtx);\n var key2 = JSON.stringify(localCtx);\n var level1 = this.cache[key1];\n if(level1 && key2 in level1) {\n return level1[key2];\n }\n return null;\n};\njsonld.ActiveContextCache.prototype.set = function(\n activeCtx, localCtx, result) {\n if(this.order.length === this.size) {\n var entry = this.order.shift();\n delete this.cache[entry.activeCtx][entry.localCtx];\n }\n var key1 = JSON.stringify(activeCtx);\n var key2 = JSON.stringify(localCtx);\n this.order.push({activeCtx: key1, localCtx: key2});\n if(!(key1 in this.cache)) {\n this.cache[key1] = {};\n }\n this.cache[key1][key2] = _clone(result);\n};\n\n/**\n * Default JSON-LD cache.\n */\njsonld.cache = {\n activeCtx: new jsonld.ActiveContextCache()\n};\n\n/**\n * Document loaders.\n */\njsonld.documentLoaders = {};\n\n/**\n * Creates a built-in jquery document loader.\n *\n * @param $ the jquery instance to use.\n * @param options the options to use:\n * secure: require all URLs to use HTTPS.\n * usePromise: true to use a promises API, false for a\n * callback-continuation-style API; defaults to true if Promise\n * is globally defined, false if not.\n *\n * @return the jquery document loader.\n */\njsonld.documentLoaders.jquery = function($, options) {\n options = options || {};\n var queue = new jsonld.RequestQueue();\n\n // use option or, by default, use Promise when its defined\n var usePromise = ('usePromise' in options ?\n options.usePromise : (typeof Promise !== 'undefined'));\n if(usePromise) {\n return queue.wrapLoader(function(url) {\n return jsonld.promisify(loader, url);\n });\n }\n return queue.wrapLoader(loader);\n\n function loader(url, callback) {\n if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; only \"http\" and \"https\" URLs are ' +\n 'supported.',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n if(options.secure && url.indexOf('https') !== 0) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; secure mode is enabled and ' +\n 'the URL\\'s scheme is not \"https\".',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n $.ajax({\n url: url,\n accepts: {\n json: 'application/ld+json, application/json'\n },\n // ensure Accept header is very specific for JSON-LD/JSON\n headers: {\n 'Accept': 'application/ld+json, application/json'\n },\n dataType: 'json',\n crossDomain: true,\n success: function(data, textStatus, jqXHR) {\n var doc = {contextUrl: null, documentUrl: url, document: data};\n\n // handle Link Header\n var contentType = jqXHR.getResponseHeader('Content-Type');\n var linkHeader = jqXHR.getResponseHeader('Link');\n if(linkHeader && contentType !== 'application/ld+json') {\n // only 1 related link header permitted\n linkHeader = jsonld.parseLinkHeader(linkHeader)[LINK_HEADER_REL];\n if(_isArray(linkHeader)) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced, it has more than one ' +\n 'associated HTTP Link Header.',\n 'jsonld.InvalidUrl',\n {code: 'multiple context link headers', url: url}), doc);\n }\n if(linkHeader) {\n doc.contextUrl = linkHeader.target;\n }\n }\n\n callback(null, doc);\n },\n error: function(jqXHR, textStatus, err) {\n callback(new JsonLdError(\n 'URL could not be dereferenced, an error occurred.',\n 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url: url, cause: err}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n });\n }\n};\n\n/**\n * Creates a built-in node document loader.\n *\n * @param options the options to use:\n * secure: require all URLs to use HTTPS.\n * strictSSL: true to require SSL certificates to be valid,\n * false not to (default: true).\n * maxRedirects: the maximum number of redirects to permit, none by\n * default.\n * request: the object which will make the request, default is\n * provided by `https://www.npmjs.com/package/request`.\n * headers: an array of headers which will be passed as request\n * headers for the requested document. Accept is not allowed.\n * usePromise: true to use a promises API, false for a\n * callback-continuation-style API; false by default.\n *\n * @return the node document loader.\n */\njsonld.documentLoaders.node = function(options) {\n options = options || {};\n var strictSSL = ('strictSSL' in options) ? options.strictSSL : true;\n var maxRedirects = ('maxRedirects' in options) ? options.maxRedirects : -1;\n var request = ('request' in options) ? options.request : require('request');\n var acceptHeader = 'application/ld+json, application/json';\n var http = require('http');\n // TODO: disable cache until HTTP caching implemented\n //var cache = new jsonld.DocumentCache();\n\n var queue = new jsonld.RequestQueue();\n if(options.usePromise) {\n return queue.wrapLoader(function(url) {\n return jsonld.promisify(loadDocument, url, []);\n });\n }\n var headers = options.headers || {};\n if('Accept' in headers || 'accept' in headers) {\n throw new RangeError(\n 'Accept header may not be specified as an option; only \"' +\n acceptHeader + '\" is supported.');\n }\n return queue.wrapLoader(function(url, callback) {\n loadDocument(url, [], callback);\n });\n\n function loadDocument(url, redirects, callback) {\n if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; only \"http\" and \"https\" URLs are ' +\n 'supported.',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n if(options.secure && url.indexOf('https') !== 0) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; secure mode is enabled and ' +\n 'the URL\\'s scheme is not \"https\".',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n // TODO: disable cache until HTTP caching implemented\n var doc = null;//cache.get(url);\n if(doc !== null) {\n return callback(null, doc);\n }\n var headers = {'Accept': acceptHeader};\n for(var k in options.headers) { headers[k] = options.headers[k]; }\n request({\n url: url,\n headers: headers,\n strictSSL: strictSSL,\n followRedirect: false\n }, handleResponse);\n\n function handleResponse(err, res, body) {\n doc = {contextUrl: null, documentUrl: url, document: body || null};\n\n // handle error\n if(err) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced, an error occurred.',\n 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url: url, cause: err}), doc);\n }\n var statusText = http.STATUS_CODES[res.statusCode];\n if(res.statusCode >= 400) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced: ' + statusText,\n 'jsonld.InvalidUrl', {\n code: 'loading document failed',\n url: url,\n httpStatusCode: res.statusCode\n }), doc);\n }\n\n // handle Link Header\n if(res.headers.link &&\n res.headers['content-type'] !== 'application/ld+json') {\n // only 1 related link header permitted\n var linkHeader = jsonld.parseLinkHeader(\n res.headers.link)[LINK_HEADER_REL];\n if(_isArray(linkHeader)) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced, it has more than one associated ' +\n 'HTTP Link Header.',\n 'jsonld.InvalidUrl',\n {code: 'multiple context link headers', url: url}), doc);\n }\n if(linkHeader) {\n doc.contextUrl = linkHeader.target;\n }\n }\n\n // handle redirect\n if(res.statusCode >= 300 && res.statusCode < 400 &&\n res.headers.location) {\n if(redirects.length === maxRedirects) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; there were too many redirects.',\n 'jsonld.TooManyRedirects', {\n code: 'loading document failed',\n url: url,\n httpStatusCode: res.statusCode,\n redirects: redirects\n }), doc);\n }\n if(redirects.indexOf(url) !== -1) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; infinite redirection was detected.',\n 'jsonld.InfiniteRedirectDetected', {\n code: 'recursive context inclusion',\n url: url,\n httpStatusCode: res.statusCode,\n redirects: redirects\n }), doc);\n }\n redirects.push(url);\n return loadDocument(res.headers.location, redirects, callback);\n }\n // cache for each redirected URL\n redirects.push(url);\n // TODO: disable cache until HTTP caching implemented\n /*for(var i = 0; i < redirects.length; ++i) {\n cache.set(\n redirects[i],\n {contextUrl: null, documentUrl: redirects[i], document: body});\n }*/\n callback(err, doc);\n }\n }\n};\n\n/**\n * Creates a built-in XMLHttpRequest document loader.\n *\n * @param options the options to use:\n * secure: require all URLs to use HTTPS.\n * usePromise: true to use a promises API, false for a\n * callback-continuation-style API; defaults to true if Promise\n * is globally defined, false if not.\n * [xhr]: the XMLHttpRequest API to use.\n *\n * @return the XMLHttpRequest document loader.\n */\njsonld.documentLoaders.xhr = function(options) {\n options = options || {};\n var rlink = /(^|(\\r\\n))link:/i;\n var queue = new jsonld.RequestQueue();\n\n // use option or, by default, use Promise when its defined\n var usePromise = ('usePromise' in options ?\n options.usePromise : (typeof Promise !== 'undefined'));\n if(usePromise) {\n return queue.wrapLoader(function(url) {\n return jsonld.promisify(loader, url);\n });\n }\n return queue.wrapLoader(loader);\n\n function loader(url, callback) {\n if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; only \"http\" and \"https\" URLs are ' +\n 'supported.',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n if(options.secure && url.indexOf('https') !== 0) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced; secure mode is enabled and ' +\n 'the URL\\'s scheme is not \"https\".',\n 'jsonld.InvalidUrl', {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n }\n var xhr = options.xhr || XMLHttpRequest;\n var req = new xhr();\n req.onload = function() {\n if(req.status >= 400) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced: ' + req.statusText,\n 'jsonld.LoadDocumentError', {\n code: 'loading document failed',\n url: url,\n httpStatusCode: req.status\n }), {contextUrl: null, documentUrl: url, document: null});\n }\n\n var doc = {contextUrl: null, documentUrl: url, document: req.response};\n\n // handle Link Header (avoid unsafe header warning by existence testing)\n var contentType = req.getResponseHeader('Content-Type');\n var linkHeader;\n if(rlink.test(req.getAllResponseHeaders())) {\n linkHeader = req.getResponseHeader('Link');\n }\n if(linkHeader && contentType !== 'application/ld+json') {\n // only 1 related link header permitted\n linkHeader = jsonld.parseLinkHeader(linkHeader)[LINK_HEADER_REL];\n if(_isArray(linkHeader)) {\n return callback(new JsonLdError(\n 'URL could not be dereferenced, it has more than one ' +\n 'associated HTTP Link Header.',\n 'jsonld.InvalidUrl',\n {code: 'multiple context link headers', url: url}), doc);\n }\n if(linkHeader) {\n doc.contextUrl = linkHeader.target;\n }\n }\n\n callback(null, doc);\n };\n req.onerror = function() {\n callback(new JsonLdError(\n 'URL could not be dereferenced, an error occurred.',\n 'jsonld.LoadDocumentError',\n {code: 'loading document failed', url: url}),\n {contextUrl: null, documentUrl: url, document: null});\n };\n req.open('GET', url, true);\n req.setRequestHeader('Accept', 'application/ld+json, application/json');\n req.send();\n }\n};\n\n/**\n * Assigns the default document loader for external document URLs to a built-in\n * default. Supported types currently include: 'jquery' and 'node'.\n *\n * To use the jquery document loader, the first parameter must be a reference\n * to the main jquery object.\n *\n * @param type the type to set.\n * @param [params] the parameters required to use the document loader.\n */\njsonld.useDocumentLoader = function(type) {\n if(!(type in jsonld.documentLoaders)) {\n throw new JsonLdError(\n 'Unknown document loader type: \"' + type + '\"',\n 'jsonld.UnknownDocumentLoader',\n {type: type});\n }\n\n // set document loader\n jsonld.documentLoader = jsonld.documentLoaders[type].apply(\n jsonld, Array.prototype.slice.call(arguments, 1));\n};\n\n/**\n * Processes a local context, resolving any URLs as necessary, and returns a\n * new active context in its callback.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context to process.\n * @param [options] the options to use:\n * [documentLoader(url, callback(err, remoteDoc))] the document loader.\n * @param callback(err, ctx) called once the operation completes.\n */\njsonld.processContext = function(activeCtx, localCtx) {\n // get arguments\n var options = {};\n var callbackArg = 2;\n if(arguments.length > 3) {\n options = arguments[2] || {};\n callbackArg += 1;\n }\n var callback = arguments[callbackArg];\n\n // set default options\n if(!('base' in options)) {\n options.base = '';\n }\n if(!('documentLoader' in options)) {\n options.documentLoader = jsonld.loadDocument;\n }\n\n // return initial context early for null context\n if(localCtx === null) {\n return callback(null, _getInitialContext(options));\n }\n\n // retrieve URLs in localCtx\n localCtx = _clone(localCtx);\n if(!(_isObject(localCtx) && '@context' in localCtx)) {\n localCtx = {'@context': localCtx};\n }\n _retrieveContextUrls(localCtx, options, function(err, ctx) {\n if(err) {\n return callback(err);\n }\n try {\n // process context\n ctx = new Processor().processContext(activeCtx, ctx, options);\n } catch(ex) {\n return callback(ex);\n }\n callback(null, ctx);\n });\n};\n\n/**\n * Returns true if the given subject has the given property.\n *\n * @param subject the subject to check.\n * @param property the property to look for.\n *\n * @return true if the subject has the given property, false if not.\n */\njsonld.hasProperty = function(subject, property) {\n var rval = false;\n if(property in subject) {\n var value = subject[property];\n rval = (!_isArray(value) || value.length > 0);\n }\n return rval;\n};\n\n/**\n * Determines if the given value is a property of the given subject.\n *\n * @param subject the subject to check.\n * @param property the property to check.\n * @param value the value to check.\n *\n * @return true if the value exists, false if not.\n */\njsonld.hasValue = function(subject, property, value) {\n var rval = false;\n if(jsonld.hasProperty(subject, property)) {\n var val = subject[property];\n var isList = _isList(val);\n if(_isArray(val) || isList) {\n if(isList) {\n val = val['@list'];\n }\n for(var i = 0; i < val.length; ++i) {\n if(jsonld.compareValues(value, val[i])) {\n rval = true;\n break;\n }\n }\n } else if(!_isArray(value)) {\n // avoid matching the set of values with an array value parameter\n rval = jsonld.compareValues(value, val);\n }\n }\n return rval;\n};\n\n/**\n * Adds a value to a subject. If the value is an array, all values in the\n * array will be added.\n *\n * @param subject the subject to add the value to.\n * @param property the property that relates the value to the subject.\n * @param value the value to add.\n * @param [options] the options to use:\n * [propertyIsArray] true if the property is always an array, false\n * if not (default: false).\n * [allowDuplicate] true to allow duplicates, false not to (uses a\n * simple shallow comparison of subject ID or value) (default: true).\n */\njsonld.addValue = function(subject, property, value, options) {\n options = options || {};\n if(!('propertyIsArray' in options)) {\n options.propertyIsArray = false;\n }\n if(!('allowDuplicate' in options)) {\n options.allowDuplicate = true;\n }\n\n if(_isArray(value)) {\n if(value.length === 0 && options.propertyIsArray &&\n !(property in subject)) {\n subject[property] = [];\n }\n for(var i = 0; i < value.length; ++i) {\n jsonld.addValue(subject, property, value[i], options);\n }\n } else if(property in subject) {\n // check if subject already has value if duplicates not allowed\n var hasValue = (!options.allowDuplicate &&\n jsonld.hasValue(subject, property, value));\n\n // make property an array if value not present or always an array\n if(!_isArray(subject[property]) &&\n (!hasValue || options.propertyIsArray)) {\n subject[property] = [subject[property]];\n }\n\n // add new value\n if(!hasValue) {\n subject[property].push(value);\n }\n } else {\n // add new value as set or single value\n subject[property] = options.propertyIsArray ? [value] : value;\n }\n};\n\n/**\n * Gets all of the values for a subject's property as an array.\n *\n * @param subject the subject.\n * @param property the property.\n *\n * @return all of the values for a subject's property as an array.\n */\njsonld.getValues = function(subject, property) {\n var rval = subject[property] || [];\n if(!_isArray(rval)) {\n rval = [rval];\n }\n return rval;\n};\n\n/**\n * Removes a property from a subject.\n *\n * @param subject the subject.\n * @param property the property.\n */\njsonld.removeProperty = function(subject, property) {\n delete subject[property];\n};\n\n/**\n * Removes a value from a subject.\n *\n * @param subject the subject.\n * @param property the property that relates the value to the subject.\n * @param value the value to remove.\n * @param [options] the options to use:\n * [propertyIsArray] true if the property is always an array, false\n * if not (default: false).\n */\njsonld.removeValue = function(subject, property, value, options) {\n options = options || {};\n if(!('propertyIsArray' in options)) {\n options.propertyIsArray = false;\n }\n\n // filter out value\n var values = jsonld.getValues(subject, property).filter(function(e) {\n return !jsonld.compareValues(e, value);\n });\n\n if(values.length === 0) {\n jsonld.removeProperty(subject, property);\n } else if(values.length === 1 && !options.propertyIsArray) {\n subject[property] = values[0];\n } else {\n subject[property] = values;\n }\n};\n\n/**\n * Compares two JSON-LD values for equality. Two JSON-LD values will be\n * considered equal if:\n *\n * 1. They are both primitives of the same type and value.\n * 2. They are both @values with the same @value, @type, @language,\n * and @index, OR\n * 3. They both have @ids they are the same.\n *\n * @param v1 the first value.\n * @param v2 the second value.\n *\n * @return true if v1 and v2 are considered equal, false if not.\n */\njsonld.compareValues = function(v1, v2) {\n // 1. equal primitives\n if(v1 === v2) {\n return true;\n }\n\n // 2. equal @values\n if(_isValue(v1) && _isValue(v2) &&\n v1['@value'] === v2['@value'] &&\n v1['@type'] === v2['@type'] &&\n v1['@language'] === v2['@language'] &&\n v1['@index'] === v2['@index']) {\n return true;\n }\n\n // 3. equal @ids\n if(_isObject(v1) && ('@id' in v1) && _isObject(v2) && ('@id' in v2)) {\n return v1['@id'] === v2['@id'];\n }\n\n return false;\n};\n\n/**\n * Gets the value for the given active context key and type, null if none is\n * set.\n *\n * @param ctx the active context.\n * @param key the context key.\n * @param [type] the type of value to get (eg: '@id', '@type'), if not\n * specified gets the entire entry for a key, null if not found.\n *\n * @return the value.\n */\njsonld.getContextValue = function(ctx, key, type) {\n var rval = null;\n\n // return null for invalid key\n if(key === null) {\n return rval;\n }\n\n // get default language\n if(type === '@language' && (type in ctx)) {\n rval = ctx[type];\n }\n\n // get specific entry information\n if(ctx.mappings[key]) {\n var entry = ctx.mappings[key];\n\n if(_isUndefined(type)) {\n // return whole entry\n rval = entry;\n } else if(type in entry) {\n // return entry value for type\n rval = entry[type];\n }\n }\n\n return rval;\n};\n\n/** Registered RDF dataset parsers hashed by content-type. */\nvar _rdfParsers = {};\n\n/**\n * Registers an RDF dataset parser by content-type, for use with\n * jsonld.fromRDF. An RDF dataset parser will always be given two parameters,\n * a string of input and a callback. An RDF dataset parser can be synchronous\n * or asynchronous.\n *\n * If the parser function returns undefined or null then it will be assumed to\n * be asynchronous w/a continuation-passing style and the callback parameter\n * given to the parser MUST be invoked.\n *\n * If it returns a Promise, then it will be assumed to be asynchronous, but the\n * callback parameter MUST NOT be invoked. It should instead be ignored.\n *\n * If it returns an RDF dataset, it will be assumed to be synchronous and the\n * callback parameter MUST NOT be invoked. It should instead be ignored.\n *\n * @param contentType the content-type for the parser.\n * @param parser(input, callback(err, dataset)) the parser function (takes a\n * string as a parameter and either returns null/undefined and uses\n * the given callback, returns a Promise, or returns an RDF dataset).\n */\njsonld.registerRDFParser = function(contentType, parser) {\n _rdfParsers[contentType] = parser;\n};\n\n/**\n * Unregisters an RDF dataset parser by content-type.\n *\n * @param contentType the content-type for the parser.\n */\njsonld.unregisterRDFParser = function(contentType) {\n delete _rdfParsers[contentType];\n};\n\nif(_nodejs) {\n // needed for serialization of XML literals\n if(typeof XMLSerializer === 'undefined') {\n var XMLSerializer = null;\n }\n if(typeof Node === 'undefined') {\n var Node = {\n ELEMENT_NODE: 1,\n ATTRIBUTE_NODE: 2,\n TEXT_NODE: 3,\n CDATA_SECTION_NODE: 4,\n ENTITY_REFERENCE_NODE: 5,\n ENTITY_NODE: 6,\n PROCESSING_INSTRUCTION_NODE: 7,\n COMMENT_NODE: 8,\n DOCUMENT_NODE: 9,\n DOCUMENT_TYPE_NODE: 10,\n DOCUMENT_FRAGMENT_NODE: 11,\n NOTATION_NODE:12\n };\n }\n}\n\n// constants\nvar XSD_BOOLEAN = 'http://www.w3.org/2001/XMLSchema#boolean';\nvar XSD_DOUBLE = 'http://www.w3.org/2001/XMLSchema#double';\nvar XSD_INTEGER = 'http://www.w3.org/2001/XMLSchema#integer';\nvar XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';\n\nvar RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';\nvar RDF_LIST = RDF + 'List';\nvar RDF_FIRST = RDF + 'first';\nvar RDF_REST = RDF + 'rest';\nvar RDF_NIL = RDF + 'nil';\nvar RDF_TYPE = RDF + 'type';\nvar RDF_PLAIN_LITERAL = RDF + 'PlainLiteral';\nvar RDF_XML_LITERAL = RDF + 'XMLLiteral';\nvar RDF_OBJECT = RDF + 'object';\nvar RDF_LANGSTRING = RDF + 'langString';\n\nvar LINK_HEADER_REL = 'http://www.w3.org/ns/json-ld#context';\nvar MAX_CONTEXT_URLS = 10;\n\n/**\n * A JSON-LD Error.\n *\n * @param msg the error message.\n * @param type the error type.\n * @param details the error details.\n */\nvar JsonLdError = function(msg, type, details) {\n if(_nodejs) {\n Error.call(this);\n Error.captureStackTrace(this, this.constructor);\n } else if(typeof Error !== 'undefined') {\n this.stack = (new Error()).stack;\n }\n this.name = type || 'jsonld.Error';\n this.message = msg || 'An unspecified JSON-LD error occurred.';\n this.details = details || {};\n};\nif(_nodejs) {\n require('util').inherits(JsonLdError, Error);\n} else if(typeof Error !== 'undefined') {\n JsonLdError.prototype = new Error();\n}\n\n/**\n * Constructs a new JSON-LD Processor.\n */\nvar Processor = function() {};\n\n/**\n * Recursively compacts an element using the given active context. All values\n * must be in expanded form before this method is called.\n *\n * @param activeCtx the active context to use.\n * @param activeProperty the compacted property associated with the element\n * to compact, null for none.\n * @param element the element to compact.\n * @param options the compaction options.\n *\n * @return the compacted value.\n */\nProcessor.prototype.compact = function(\n activeCtx, activeProperty, element, options) {\n // recursively compact array\n if(_isArray(element)) {\n var rval = [];\n for(var i = 0; i < element.length; ++i) {\n // compact, dropping any null values\n var compacted = this.compact(\n activeCtx, activeProperty, element[i], options);\n if(compacted !== null) {\n rval.push(compacted);\n }\n }\n if(options.compactArrays && rval.length === 1) {\n // use single element if no container is specified\n var container = jsonld.getContextValue(\n activeCtx, activeProperty, '@container');\n if(container === null) {\n rval = rval[0];\n }\n }\n return rval;\n }\n\n // recursively compact object\n if(_isObject(element)) {\n if(options.link && '@id' in element && element['@id'] in options.link) {\n // check for a linked element to reuse\n var linked = options.link[element['@id']];\n for(var i = 0; i < linked.length; ++i) {\n if(linked[i].expanded === element) {\n return linked[i].compacted;\n }\n }\n }\n\n // do value compaction on @values and subject references\n if(_isValue(element) || _isSubjectReference(element)) {\n var rval = _compactValue(activeCtx, activeProperty, element);\n if(options.link && _isSubjectReference(element)) {\n // store linked element\n if(!(element['@id'] in options.link)) {\n options.link[element['@id']] = [];\n }\n options.link[element['@id']].push({expanded: element, compacted: rval});\n }\n return rval;\n }\n\n // FIXME: avoid misuse of active property as an expanded property?\n var insideReverse = (activeProperty === '@reverse');\n\n var rval = {};\n\n if(options.link && '@id' in element) {\n // store linked element\n if(!(element['@id'] in options.link)) {\n options.link[element['@id']] = [];\n }\n options.link[element['@id']].push({expanded: element, compacted: rval});\n }\n\n // process element keys in order\n var keys = Object.keys(element).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var expandedProperty = keys[ki];\n var expandedValue = element[expandedProperty];\n\n // compact @id and @type(s)\n if(expandedProperty === '@id' || expandedProperty === '@type') {\n var compactedValue;\n\n // compact single @id\n if(_isString(expandedValue)) {\n compactedValue = _compactIri(\n activeCtx, expandedValue, null,\n {vocab: (expandedProperty === '@type')});\n } else {\n // expanded value must be a @type array\n compactedValue = [];\n for(var vi = 0; vi < expandedValue.length; ++vi) {\n compactedValue.push(_compactIri(\n activeCtx, expandedValue[vi], null, {vocab: true}));\n }\n }\n\n // use keyword alias and add value\n var alias = _compactIri(activeCtx, expandedProperty);\n var isArray = (_isArray(compactedValue) && expandedValue.length === 0);\n jsonld.addValue(\n rval, alias, compactedValue, {propertyIsArray: isArray});\n continue;\n }\n\n // handle @reverse\n if(expandedProperty === '@reverse') {\n // recursively compact expanded value\n var compactedValue = this.compact(\n activeCtx, '@reverse', expandedValue, options);\n\n // handle double-reversed properties\n for(var compactedProperty in compactedValue) {\n if(activeCtx.mappings[compactedProperty] &&\n activeCtx.mappings[compactedProperty].reverse) {\n var value = compactedValue[compactedProperty];\n var container = jsonld.getContextValue(\n activeCtx, compactedProperty, '@container');\n var useArray = (container === '@set' || !options.compactArrays);\n jsonld.addValue(\n rval, compactedProperty, value, {propertyIsArray: useArray});\n delete compactedValue[compactedProperty];\n }\n }\n\n if(Object.keys(compactedValue).length > 0) {\n // use keyword alias and add value\n var alias = _compactIri(activeCtx, expandedProperty);\n jsonld.addValue(rval, alias, compactedValue);\n }\n\n continue;\n }\n\n // handle @index property\n if(expandedProperty === '@index') {\n // drop @index if inside an @index container\n var container = jsonld.getContextValue(\n activeCtx, activeProperty, '@container');\n if(container === '@index') {\n continue;\n }\n\n // use keyword alias and add value\n var alias = _compactIri(activeCtx, expandedProperty);\n jsonld.addValue(rval, alias, expandedValue);\n continue;\n }\n\n // skip array processing for keywords that aren't @graph or @list\n if(expandedProperty !== '@graph' && expandedProperty !== '@list' &&\n _isKeyword(expandedProperty)) {\n // use keyword alias and add value as is\n var alias = _compactIri(activeCtx, expandedProperty);\n jsonld.addValue(rval, alias, expandedValue);\n continue;\n }\n\n // Note: expanded value must be an array due to expansion algorithm.\n\n // preserve empty arrays\n if(expandedValue.length === 0) {\n var itemActiveProperty = _compactIri(\n activeCtx, expandedProperty, expandedValue, {vocab: true},\n insideReverse);\n jsonld.addValue(\n rval, itemActiveProperty, expandedValue, {propertyIsArray: true});\n }\n\n // recusively process array values\n for(var vi = 0; vi < expandedValue.length; ++vi) {\n var expandedItem = expandedValue[vi];\n\n // compact property and get container type\n var itemActiveProperty = _compactIri(\n activeCtx, expandedProperty, expandedItem, {vocab: true},\n insideReverse);\n var container = jsonld.getContextValue(\n activeCtx, itemActiveProperty, '@container');\n\n // get @list value if appropriate\n var isList = _isList(expandedItem);\n var list = null;\n if(isList) {\n list = expandedItem['@list'];\n }\n\n // recursively compact expanded item\n var compactedItem = this.compact(\n activeCtx, itemActiveProperty, isList ? list : expandedItem, options);\n\n // handle @list\n if(isList) {\n // ensure @list value is an array\n if(!_isArray(compactedItem)) {\n compactedItem = [compactedItem];\n }\n\n if(container !== '@list') {\n // wrap using @list alias\n var wrapper = {};\n wrapper[_compactIri(activeCtx, '@list')] = compactedItem;\n compactedItem = wrapper;\n\n // include @index from expanded @list, if any\n if('@index' in expandedItem) {\n compactedItem[_compactIri(activeCtx, '@index')] =\n expandedItem['@index'];\n }\n } else if(itemActiveProperty in rval) {\n // can't use @list container for more than 1 list\n throw new JsonLdError(\n 'JSON-LD compact error; property has a \"@list\" @container ' +\n 'rule but there is more than a single @list that matches ' +\n 'the compacted term in the document. Compaction might mix ' +\n 'unwanted items into the list.',\n 'jsonld.SyntaxError', {code: 'compaction to list of lists'});\n }\n }\n\n // handle language and index maps\n if(container === '@language' || container === '@index') {\n // get or create the map object\n var mapObject;\n if(itemActiveProperty in rval) {\n mapObject = rval[itemActiveProperty];\n } else {\n rval[itemActiveProperty] = mapObject = {};\n }\n\n // if container is a language map, simplify compacted value to\n // a simple string\n if(container === '@language' && _isValue(compactedItem)) {\n compactedItem = compactedItem['@value'];\n }\n\n // add compact value to map object using key from expanded value\n // based on the container type\n jsonld.addValue(mapObject, expandedItem[container], compactedItem);\n } else {\n // use an array if: compactArrays flag is false,\n // @container is @set or @list , value is an empty\n // array, or key is @graph\n var isArray = (!options.compactArrays || container === '@set' ||\n container === '@list' ||\n (_isArray(compactedItem) && compactedItem.length === 0) ||\n expandedProperty === '@list' || expandedProperty === '@graph');\n\n // add compact value\n jsonld.addValue(\n rval, itemActiveProperty, compactedItem,\n {propertyIsArray: isArray});\n }\n }\n }\n\n return rval;\n }\n\n // only primitives remain which are already compact\n return element;\n};\n\n/**\n * Recursively expands an element using the given context. Any context in\n * the element will be removed. All context URLs must have been retrieved\n * before calling this method.\n *\n * @param activeCtx the context to use.\n * @param activeProperty the property for the element, null for none.\n * @param element the element to expand.\n * @param options the expansion options.\n * @param insideList true if the element is a list, false if not.\n *\n * @return the expanded value.\n */\nProcessor.prototype.expand = function(\n activeCtx, activeProperty, element, options, insideList) {\n var self = this;\n\n // nothing to expand\n if(element === null || element === undefined) {\n return null;\n }\n\n if(!_isArray(element) && !_isObject(element)) {\n // drop free-floating scalars that are not in lists\n if(!insideList && (activeProperty === null ||\n _expandIri(activeCtx, activeProperty, {vocab: true}) === '@graph')) {\n return null;\n }\n\n // expand element according to value expansion rules\n return _expandValue(activeCtx, activeProperty, element);\n }\n\n // recursively expand array\n if(_isArray(element)) {\n var rval = [];\n var container = jsonld.getContextValue(\n activeCtx, activeProperty, '@container');\n insideList = insideList || container === '@list';\n for(var i = 0; i < element.length; ++i) {\n // expand element\n var e = self.expand(activeCtx, activeProperty, element[i], options);\n if(insideList && (_isArray(e) || _isList(e))) {\n // lists of lists are illegal\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; lists of lists are not permitted.',\n 'jsonld.SyntaxError', {code: 'list of lists'});\n }\n // drop null values\n if(e !== null) {\n if(_isArray(e)) {\n rval = rval.concat(e);\n } else {\n rval.push(e);\n }\n }\n }\n return rval;\n }\n\n // recursively expand object:\n\n // if element has a context, process it\n if('@context' in element) {\n activeCtx = self.processContext(activeCtx, element['@context'], options);\n }\n\n // expand the active property\n var expandedActiveProperty = _expandIri(\n activeCtx, activeProperty, {vocab: true});\n\n var rval = {};\n var keys = Object.keys(element).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var key = keys[ki];\n var value = element[key];\n var expandedValue;\n\n // skip @context\n if(key === '@context') {\n continue;\n }\n\n // expand property\n var expandedProperty = _expandIri(activeCtx, key, {vocab: true});\n\n // drop non-absolute IRI keys that aren't keywords\n if(expandedProperty === null ||\n !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) {\n continue;\n }\n\n if(_isKeyword(expandedProperty)) {\n if(expandedActiveProperty === '@reverse') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' +\n 'property.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property map', value: value});\n }\n if(expandedProperty in rval) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; colliding keywords detected.',\n 'jsonld.SyntaxError',\n {code: 'colliding keywords', keyword: expandedProperty});\n }\n }\n\n // syntax error if @id is not a string\n if(expandedProperty === '@id' && !_isString(value)) {\n if(!options.isFrame) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value must a string.',\n 'jsonld.SyntaxError', {code: 'invalid @id value', value: value});\n }\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@id\" value must be a string or an ' +\n 'object.', 'jsonld.SyntaxError',\n {code: 'invalid @id value', value: value});\n }\n }\n\n if(expandedProperty === '@type') {\n _validateTypeValue(value);\n }\n\n // @graph must be an array or an object\n if(expandedProperty === '@graph' &&\n !(_isObject(value) || _isArray(value))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@graph\" value must not be an ' +\n 'object or an array.',\n 'jsonld.SyntaxError', {code: 'invalid @graph value', value: value});\n }\n\n // @value must not be an object or an array\n if(expandedProperty === '@value' &&\n (_isObject(value) || _isArray(value))) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@value\" value must not be an ' +\n 'object or an array.',\n 'jsonld.SyntaxError',\n {code: 'invalid value object value', value: value});\n }\n\n // @language must be a string\n if(expandedProperty === '@language') {\n if(value === null) {\n // drop null @language values, they expand as if they didn't exist\n continue;\n }\n if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@language\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid language-tagged string', value: value});\n }\n // ensure language value is lowercase\n value = value.toLowerCase();\n }\n\n // @index must be a string\n if(expandedProperty === '@index') {\n if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@index\" value must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid @index value', value: value});\n }\n }\n\n // @reverse must be an object\n if(expandedProperty === '@reverse') {\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must be an object.',\n 'jsonld.SyntaxError', {code: 'invalid @reverse value', value: value});\n }\n\n expandedValue = self.expand(activeCtx, '@reverse', value, options);\n\n // properties double-reversed\n if('@reverse' in expandedValue) {\n for(var property in expandedValue['@reverse']) {\n jsonld.addValue(\n rval, property, expandedValue['@reverse'][property],\n {propertyIsArray: true});\n }\n }\n\n // FIXME: can this be merged with code below to simplify?\n // merge in all reversed properties\n var reverseMap = rval['@reverse'] || null;\n for(var property in expandedValue) {\n if(property === '@reverse') {\n continue;\n }\n if(reverseMap === null) {\n reverseMap = rval['@reverse'] = {};\n }\n jsonld.addValue(reverseMap, property, [], {propertyIsArray: true});\n var items = expandedValue[property];\n for(var ii = 0; ii < items.length; ++ii) {\n var item = items[ii];\n if(_isValue(item) || _isList(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must not be a ' +\n '@value or an @list.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property value', value: expandedValue});\n }\n jsonld.addValue(\n reverseMap, property, item, {propertyIsArray: true});\n }\n }\n\n continue;\n }\n\n var container = jsonld.getContextValue(activeCtx, key, '@container');\n\n if(container === '@language' && _isObject(value)) {\n // handle language map container (skip if value is not an object)\n expandedValue = _expandLanguageMap(value);\n } else if(container === '@index' && _isObject(value)) {\n // handle index container (skip if value is not an object)\n expandedValue = (function _expandIndexMap(activeProperty) {\n var rval = [];\n var keys = Object.keys(value).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var key = keys[ki];\n var val = value[key];\n if(!_isArray(val)) {\n val = [val];\n }\n val = self.expand(activeCtx, activeProperty, val, options, false);\n for(var vi = 0; vi < val.length; ++vi) {\n var item = val[vi];\n if(!('@index' in item)) {\n item['@index'] = key;\n }\n rval.push(item);\n }\n }\n return rval;\n })(key);\n } else {\n // recurse into @list or @set\n var isList = (expandedProperty === '@list');\n if(isList || expandedProperty === '@set') {\n var nextActiveProperty = activeProperty;\n if(isList && expandedActiveProperty === '@graph') {\n nextActiveProperty = null;\n }\n expandedValue = self.expand(\n activeCtx, nextActiveProperty, value, options, isList);\n if(isList && _isList(expandedValue)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; lists of lists are not permitted.',\n 'jsonld.SyntaxError', {code: 'list of lists'});\n }\n } else {\n // recursively expand value with key as new active property\n expandedValue = self.expand(activeCtx, key, value, options, false);\n }\n }\n\n // drop null values if property is not @value\n if(expandedValue === null && expandedProperty !== '@value') {\n continue;\n }\n\n // convert expanded value to @list if container specifies it\n if(expandedProperty !== '@list' && !_isList(expandedValue) &&\n container === '@list') {\n // ensure expanded value is an array\n expandedValue = (_isArray(expandedValue) ?\n expandedValue : [expandedValue]);\n expandedValue = {'@list': expandedValue};\n }\n\n // FIXME: can this be merged with code above to simplify?\n // merge in reverse properties\n if(activeCtx.mappings[key] && activeCtx.mappings[key].reverse) {\n var reverseMap = rval['@reverse'] = rval['@reverse'] || {};\n if(!_isArray(expandedValue)) {\n expandedValue = [expandedValue];\n }\n for(var ii = 0; ii < expandedValue.length; ++ii) {\n var item = expandedValue[ii];\n if(_isValue(item) || _isList(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@reverse\" value must not be a ' +\n '@value or an @list.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property value', value: expandedValue});\n }\n jsonld.addValue(\n reverseMap, expandedProperty, item, {propertyIsArray: true});\n }\n continue;\n }\n\n // add value for property\n // use an array except for certain keywords\n var useArray =\n ['@index', '@id', '@type', '@value', '@language'].indexOf(\n expandedProperty) === -1;\n jsonld.addValue(\n rval, expandedProperty, expandedValue, {propertyIsArray: useArray});\n }\n\n // get property count on expanded output\n keys = Object.keys(rval);\n var count = keys.length;\n\n if('@value' in rval) {\n // @value must only have @language or @type\n if('@type' in rval && '@language' in rval) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" may not ' +\n 'contain both \"@type\" and \"@language\".',\n 'jsonld.SyntaxError', {code: 'invalid value object', element: rval});\n }\n var validCount = count - 1;\n if('@type' in rval) {\n validCount -= 1;\n }\n if('@index' in rval) {\n validCount -= 1;\n }\n if('@language' in rval) {\n validCount -= 1;\n }\n if(validCount !== 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" may only ' +\n 'have an \"@index\" property and at most one other property ' +\n 'which can be \"@type\" or \"@language\".',\n 'jsonld.SyntaxError', {code: 'invalid value object', element: rval});\n }\n // drop null @values\n if(rval['@value'] === null) {\n rval = null;\n } else if('@language' in rval && !_isString(rval['@value'])) {\n // if @language is present, @value must be a string\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; only strings may be language-tagged.',\n 'jsonld.SyntaxError',\n {code: 'invalid language-tagged value', element: rval});\n } else if('@type' in rval && (!_isAbsoluteIri(rval['@type']) ||\n rval['@type'].indexOf('_:') === 0)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an element containing \"@value\" and \"@type\" ' +\n 'must have an absolute IRI for the value of \"@type\".',\n 'jsonld.SyntaxError', {code: 'invalid typed value', element: rval});\n }\n } else if('@type' in rval && !_isArray(rval['@type'])) {\n // convert @type to an array\n rval['@type'] = [rval['@type']];\n } else if('@set' in rval || '@list' in rval) {\n // handle @set and @list\n if(count > 1 && !(count === 2 && '@index' in rval)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; if an element has the property \"@set\" ' +\n 'or \"@list\", then it can have at most one other property that is ' +\n '\"@index\".', 'jsonld.SyntaxError',\n {code: 'invalid set or list object', element: rval});\n }\n // optimize away @set\n if('@set' in rval) {\n rval = rval['@set'];\n keys = Object.keys(rval);\n count = keys.length;\n }\n } else if(count === 1 && '@language' in rval) {\n // drop objects with only @language\n rval = null;\n }\n\n // drop certain top-level objects that do not occur in lists\n if(_isObject(rval) &&\n !options.keepFreeFloatingNodes && !insideList &&\n (activeProperty === null || expandedActiveProperty === '@graph')) {\n // drop empty object, top-level @value/@list, or object with only @id\n if(count === 0 || '@value' in rval || '@list' in rval ||\n (count === 1 && '@id' in rval)) {\n rval = null;\n }\n }\n\n return rval;\n};\n\n/**\n * Creates a JSON-LD node map (node ID => node).\n *\n * @param input the expanded JSON-LD to create a node map of.\n * @param [options] the options to use:\n * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes.\n * [namer] (deprecated).\n *\n * @return the node map.\n */\nProcessor.prototype.createNodeMap = function(input, options) {\n options = options || {};\n\n // produce a map of all subjects and name each bnode\n var issuer = options.namer || options.issuer || new IdentifierIssuer('_:b');\n var graphs = {'@default': {}};\n _createNodeMap(input, graphs, '@default', issuer);\n\n // add all non-default graphs to default graph\n return _mergeNodeMaps(graphs);\n};\n\n/**\n * Performs JSON-LD flattening.\n *\n * @param input the expanded JSON-LD to flatten.\n *\n * @return the flattened output.\n */\nProcessor.prototype.flatten = function(input) {\n var defaultGraph = this.createNodeMap(input);\n\n // produce flattened output\n var flattened = [];\n var keys = Object.keys(defaultGraph).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var node = defaultGraph[keys[ki]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n flattened.push(node);\n }\n }\n return flattened;\n};\n\n/**\n * Performs JSON-LD framing.\n *\n * @param input the expanded JSON-LD to frame.\n * @param frame the expanded JSON-LD frame to use.\n * @param options the framing options.\n *\n * @return the framed output.\n */\nProcessor.prototype.frame = function(input, frame, options) {\n // create framing state\n var state = {\n options: options,\n graphs: {'@default': {}, '@merged': {}},\n subjectStack: [],\n link: {}\n };\n\n // produce a map of all graphs and name each bnode\n // FIXME: currently uses subjects from @merged graph only\n var issuer = new IdentifierIssuer('_:b');\n _createNodeMap(input, state.graphs, '@merged', issuer);\n state.subjects = state.graphs['@merged'];\n\n // frame the subjects\n var framed = [];\n _frame(state, Object.keys(state.subjects).sort(), frame, framed, null);\n return framed;\n};\n\n/**\n * Performs normalization on the given RDF dataset.\n *\n * @param dataset the RDF dataset to normalize.\n * @param options the normalization options.\n * @param callback(err, normalized) called once the operation completes.\n */\nProcessor.prototype.normalize = function(dataset, options, callback) {\n if(options.algorithm === 'URDNA2015') {\n return new URDNA2015(options).main(dataset, callback);\n }\n if(options.algorithm === 'URGNA2012') {\n return new URGNA2012(options).main(dataset, callback);\n }\n callback(new Error(\n 'Invalid RDF Dataset Normalization algorithm: ' + options.algorithm));\n};\n\n/**\n * Converts an RDF dataset to JSON-LD.\n *\n * @param dataset the RDF dataset.\n * @param options the RDF serialization options.\n * @param callback(err, output) called once the operation completes.\n */\nProcessor.prototype.fromRDF = function(dataset, options, callback) {\n var defaultGraph = {};\n var graphMap = {'@default': defaultGraph};\n var referencedOnce = {};\n\n for(var name in dataset) {\n var graph = dataset[name];\n if(!(name in graphMap)) {\n graphMap[name] = {};\n }\n if(name !== '@default' && !(name in defaultGraph)) {\n defaultGraph[name] = {'@id': name};\n }\n var nodeMap = graphMap[name];\n for(var ti = 0; ti < graph.length; ++ti) {\n var triple = graph[ti];\n\n // get subject, predicate, object\n var s = triple.subject.value;\n var p = triple.predicate.value;\n var o = triple.object;\n\n if(!(s in nodeMap)) {\n nodeMap[s] = {'@id': s};\n }\n var node = nodeMap[s];\n\n var objectIsId = (o.type === 'IRI' || o.type === 'blank node');\n if(objectIsId && !(o.value in nodeMap)) {\n nodeMap[o.value] = {'@id': o.value};\n }\n\n if(p === RDF_TYPE && !options.useRdfType && objectIsId) {\n jsonld.addValue(node, '@type', o.value, {propertyIsArray: true});\n continue;\n }\n\n var value = _RDFToObject(o, options.useNativeTypes);\n jsonld.addValue(node, p, value, {propertyIsArray: true});\n\n // object may be an RDF list/partial list node but we can't know easily\n // until all triples are read\n if(objectIsId) {\n if(o.value === RDF_NIL) {\n // track rdf:nil uniquely per graph\n var object = nodeMap[o.value];\n if(!('usages' in object)) {\n object.usages = [];\n }\n object.usages.push({\n node: node,\n property: p,\n value: value\n });\n } else if(o.value in referencedOnce) {\n // object referenced more than once\n referencedOnce[o.value] = false;\n } else {\n // keep track of single reference\n referencedOnce[o.value] = {\n node: node,\n property: p,\n value: value\n };\n }\n }\n }\n }\n\n // convert linked lists to @list arrays\n for(var name in graphMap) {\n var graphObject = graphMap[name];\n\n // no @lists to be converted, continue\n if(!(RDF_NIL in graphObject)) {\n continue;\n }\n\n // iterate backwards through each RDF list\n var nil = graphObject[RDF_NIL];\n for(var i = 0; i < nil.usages.length; ++i) {\n var usage = nil.usages[i];\n var node = usage.node;\n var property = usage.property;\n var head = usage.value;\n var list = [];\n var listNodes = [];\n\n // ensure node is a well-formed list node; it must:\n // 1. Be referenced only once.\n // 2. Have an array for rdf:first that has 1 item.\n // 3. Have an array for rdf:rest that has 1 item.\n // 4. Have no keys other than: @id, rdf:first, rdf:rest, and,\n // optionally, @type where the value is rdf:List.\n var nodeKeyCount = Object.keys(node).length;\n while(property === RDF_REST &&\n _isObject(referencedOnce[node['@id']]) &&\n _isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 &&\n _isArray(node[RDF_REST]) && node[RDF_REST].length === 1 &&\n (nodeKeyCount === 3 || (nodeKeyCount === 4 && _isArray(node['@type']) &&\n node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) {\n list.push(node[RDF_FIRST][0]);\n listNodes.push(node['@id']);\n\n // get next node, moving backwards through list\n usage = referencedOnce[node['@id']];\n node = usage.node;\n property = usage.property;\n head = usage.value;\n nodeKeyCount = Object.keys(node).length;\n\n // if node is not a blank node, then list head found\n if(node['@id'].indexOf('_:') !== 0) {\n break;\n }\n }\n\n // the list is nested in another list\n if(property === RDF_FIRST) {\n // empty list\n if(node['@id'] === RDF_NIL) {\n // can't convert rdf:nil to a @list object because it would\n // result in a list of lists which isn't supported\n continue;\n }\n\n // preserve list head\n head = graphObject[head['@id']][RDF_REST][0];\n list.pop();\n listNodes.pop();\n }\n\n // transform list into @list object\n delete head['@id'];\n head['@list'] = list.reverse();\n for(var j = 0; j < listNodes.length; ++j) {\n delete graphObject[listNodes[j]];\n }\n }\n\n delete nil.usages;\n }\n\n var result = [];\n var subjects = Object.keys(defaultGraph).sort();\n for(var i = 0; i < subjects.length; ++i) {\n var subject = subjects[i];\n var node = defaultGraph[subject];\n if(subject in graphMap) {\n var graph = node['@graph'] = [];\n var graphObject = graphMap[subject];\n var subjects_ = Object.keys(graphObject).sort();\n for(var si = 0; si < subjects_.length; ++si) {\n var node_ = graphObject[subjects_[si]];\n // only add full subjects to top-level\n if(!_isSubjectReference(node_)) {\n graph.push(node_);\n }\n }\n }\n // only add full subjects to top-level\n if(!_isSubjectReference(node)) {\n result.push(node);\n }\n }\n\n callback(null, result);\n};\n\n/**\n * Outputs an RDF dataset for the expanded JSON-LD input.\n *\n * @param input the expanded JSON-LD input.\n * @param options the RDF serialization options.\n *\n * @return the RDF dataset.\n */\nProcessor.prototype.toRDF = function(input, options) {\n // create node map for default graph (and any named graphs)\n var issuer = new IdentifierIssuer('_:b');\n var nodeMap = {'@default': {}};\n _createNodeMap(input, nodeMap, '@default', issuer);\n\n var dataset = {};\n var graphNames = Object.keys(nodeMap).sort();\n for(var i = 0; i < graphNames.length; ++i) {\n var graphName = graphNames[i];\n // skip relative IRIs\n if(graphName === '@default' || _isAbsoluteIri(graphName)) {\n dataset[graphName] = _graphToRDF(nodeMap[graphName], issuer, options);\n }\n }\n return dataset;\n};\n\n/**\n * Processes a local context and returns a new active context.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context to process.\n * @param options the context processing options.\n *\n * @return the new active context.\n */\nProcessor.prototype.processContext = function(activeCtx, localCtx, options) {\n // normalize local context to an array of @context objects\n if(_isObject(localCtx) && '@context' in localCtx &&\n _isArray(localCtx['@context'])) {\n localCtx = localCtx['@context'];\n }\n var ctxs = _isArray(localCtx) ? localCtx : [localCtx];\n\n // no contexts in array, clone existing context\n if(ctxs.length === 0) {\n return activeCtx.clone();\n }\n\n // process each context in order, update active context\n // on each iteration to ensure proper caching\n var rval = activeCtx;\n for(var i = 0; i < ctxs.length; ++i) {\n var ctx = ctxs[i];\n\n // reset to initial context\n if(ctx === null) {\n rval = activeCtx = _getInitialContext(options);\n continue;\n }\n\n // dereference @context key if present\n if(_isObject(ctx) && '@context' in ctx) {\n ctx = ctx['@context'];\n }\n\n // context must be an object by now, all URLs retrieved before this call\n if(!_isObject(ctx)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context must be an object.',\n 'jsonld.SyntaxError', {code: 'invalid local context', context: ctx});\n }\n\n // get context from cache if available\n if(jsonld.cache.activeCtx) {\n var cached = jsonld.cache.activeCtx.get(activeCtx, ctx);\n if(cached) {\n rval = activeCtx = cached;\n continue;\n }\n }\n\n // update active context and clone new one before updating\n activeCtx = rval;\n rval = rval.clone();\n\n // define context mappings for keys in local context\n var defined = {};\n\n // handle @base\n if('@base' in ctx) {\n var base = ctx['@base'];\n\n // clear base\n if(base === null) {\n base = null;\n } else if(!_isString(base)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@base\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx});\n } else if(base !== '' && !_isAbsoluteIri(base)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@base\" in a ' +\n '@context must be an absolute IRI or the empty string.',\n 'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx});\n }\n\n if(base !== null) {\n base = jsonld.url.parse(base || '');\n }\n rval['@base'] = base;\n defined['@base'] = true;\n }\n\n // handle @vocab\n if('@vocab' in ctx) {\n var value = ctx['@vocab'];\n if(value === null) {\n delete rval['@vocab'];\n } else if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@vocab\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});\n } else if(!_isAbsoluteIri(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@vocab\" in a ' +\n '@context must be an absolute IRI.',\n 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx});\n } else {\n rval['@vocab'] = value;\n }\n defined['@vocab'] = true;\n }\n\n // handle @language\n if('@language' in ctx) {\n var value = ctx['@language'];\n if(value === null) {\n delete rval['@language'];\n } else if(!_isString(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; the value of \"@language\" in a ' +\n '@context must be a string or null.',\n 'jsonld.SyntaxError',\n {code: 'invalid default language', context: ctx});\n } else {\n rval['@language'] = value.toLowerCase();\n }\n defined['@language'] = true;\n }\n\n // process all other keys\n for(var key in ctx) {\n _createTermDefinition(rval, ctx, key, defined);\n }\n\n // cache result\n if(jsonld.cache.activeCtx) {\n jsonld.cache.activeCtx.set(activeCtx, ctx, rval);\n }\n }\n\n return rval;\n};\n\n/**\n * Expands a language map.\n *\n * @param languageMap the language map to expand.\n *\n * @return the expanded language map.\n */\nfunction _expandLanguageMap(languageMap) {\n var rval = [];\n var keys = Object.keys(languageMap).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var key = keys[ki];\n var val = languageMap[key];\n if(!_isArray(val)) {\n val = [val];\n }\n for(var vi = 0; vi < val.length; ++vi) {\n var item = val[vi];\n if(item === null) {\n // null values are allowed (8.5) but ignored (3.1)\n continue;\n }\n if(!_isString(item)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; language map values must be strings.',\n 'jsonld.SyntaxError',\n {code: 'invalid language map value', languageMap: languageMap});\n }\n rval.push({\n '@value': item,\n '@language': key.toLowerCase()\n });\n }\n }\n return rval;\n}\n\n/**\n * Labels the blank nodes in the given value using the given IdentifierIssuer.\n *\n * @param issuer the IdentifierIssuer to use.\n * @param element the element with blank nodes to rename.\n *\n * @return the element.\n */\nfunction _labelBlankNodes(issuer, element) {\n if(_isArray(element)) {\n for(var i = 0; i < element.length; ++i) {\n element[i] = _labelBlankNodes(issuer, element[i]);\n }\n } else if(_isList(element)) {\n element['@list'] = _labelBlankNodes(issuer, element['@list']);\n } else if(_isObject(element)) {\n // relabel blank node\n if(_isBlankNode(element)) {\n element['@id'] = issuer.getId(element['@id']);\n }\n\n // recursively apply to all keys\n var keys = Object.keys(element).sort();\n for(var ki = 0; ki < keys.length; ++ki) {\n var key = keys[ki];\n if(key !== '@id') {\n element[key] = _labelBlankNodes(issuer, element[key]);\n }\n }\n }\n\n return element;\n}\n\n/**\n * Expands the given value by using the coercion and keyword rules in the\n * given context.\n *\n * @param activeCtx the active context to use.\n * @param activeProperty the active property the value is associated with.\n * @param value the value to expand.\n *\n * @return the expanded value.\n */\nfunction _expandValue(activeCtx, activeProperty, value) {\n // nothing to expand\n if(value === null || value === undefined) {\n return null;\n }\n\n // special-case expand @id and @type (skips '@id' expansion)\n var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});\n if(expandedProperty === '@id') {\n return _expandIri(activeCtx, value, {base: true});\n } else if(expandedProperty === '@type') {\n return _expandIri(activeCtx, value, {vocab: true, base: true});\n }\n\n // get type definition from context\n var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');\n\n // do @id expansion (automatic for @graph)\n if(type === '@id' || (expandedProperty === '@graph' && _isString(value))) {\n return {'@id': _expandIri(activeCtx, value, {base: true})};\n }\n // do @id expansion w/vocab\n if(type === '@vocab') {\n return {'@id': _expandIri(activeCtx, value, {vocab: true, base: true})};\n }\n\n // do not expand keyword values\n if(_isKeyword(expandedProperty)) {\n return value;\n }\n\n var rval = {};\n\n if(type !== null) {\n // other type\n rval['@type'] = type;\n } else if(_isString(value)) {\n // check for language tagging for strings\n var language = jsonld.getContextValue(\n activeCtx, activeProperty, '@language');\n if(language !== null) {\n rval['@language'] = language;\n }\n }\n // do conversion of values that aren't basic JSON types to strings\n if(['boolean', 'number', 'string'].indexOf(typeof value) === -1) {\n value = value.toString();\n }\n rval['@value'] = value;\n\n return rval;\n}\n\n/**\n * Creates an array of RDF triples for the given graph.\n *\n * @param graph the graph to create RDF triples for.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param options the RDF serialization options.\n *\n * @return the array of RDF triples for the given graph.\n */\nfunction _graphToRDF(graph, issuer, options) {\n var rval = [];\n\n var ids = Object.keys(graph).sort();\n for(var i = 0; i < ids.length; ++i) {\n var id = ids[i];\n var node = graph[id];\n var properties = Object.keys(node).sort();\n for(var pi = 0; pi < properties.length; ++pi) {\n var property = properties[pi];\n var items = node[property];\n if(property === '@type') {\n property = RDF_TYPE;\n } else if(_isKeyword(property)) {\n continue;\n }\n\n for(var ii = 0; ii < items.length; ++ii) {\n var item = items[ii];\n\n // RDF subject\n var subject = {};\n subject.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';\n subject.value = id;\n\n // skip relative IRI subjects\n if(!_isAbsoluteIri(id)) {\n continue;\n }\n\n // RDF predicate\n var predicate = {};\n predicate.type = (property.indexOf('_:') === 0) ? 'blank node' : 'IRI';\n predicate.value = property;\n\n // skip relative IRI predicates\n if(!_isAbsoluteIri(property)) {\n continue;\n }\n\n // skip blank node predicates unless producing generalized RDF\n if(predicate.type === 'blank node' && !options.produceGeneralizedRdf) {\n continue;\n }\n\n // convert @list to triples\n if(_isList(item)) {\n _listToRDF(item['@list'], issuer, subject, predicate, rval);\n } else {\n // convert value or node object to triple\n var object = _objectToRDF(item);\n // skip null objects (they are relative IRIs)\n if(object) {\n rval.push({subject: subject, predicate: predicate, object: object});\n }\n }\n }\n }\n }\n\n return rval;\n}\n\n/**\n * Converts a @list value into linked list of blank node RDF triples\n * (an RDF collection).\n *\n * @param list the @list value.\n * @param issuer a IdentifierIssuer for assigning blank node names.\n * @param subject the subject for the head of the list.\n * @param predicate the predicate for the head of the list.\n * @param triples the array of triples to append to.\n */\nfunction _listToRDF(list, issuer, subject, predicate, triples) {\n var first = {type: 'IRI', value: RDF_FIRST};\n var rest = {type: 'IRI', value: RDF_REST};\n var nil = {type: 'IRI', value: RDF_NIL};\n\n for(var i = 0; i < list.length; ++i) {\n var item = list[i];\n\n var blankNode = {type: 'blank node', value: issuer.getId()};\n triples.push({subject: subject, predicate: predicate, object: blankNode});\n\n subject = blankNode;\n predicate = first;\n var object = _objectToRDF(item);\n\n // skip null objects (they are relative IRIs)\n if(object) {\n triples.push({subject: subject, predicate: predicate, object: object});\n }\n\n predicate = rest;\n }\n\n triples.push({subject: subject, predicate: predicate, object: nil});\n}\n\n/**\n * Converts a JSON-LD value object to an RDF literal or a JSON-LD string or\n * node object to an RDF resource.\n *\n * @param item the JSON-LD value or node object.\n *\n * @return the RDF literal or RDF resource.\n */\nfunction _objectToRDF(item) {\n var object = {};\n\n // convert value object to RDF\n if(_isValue(item)) {\n object.type = 'literal';\n var value = item['@value'];\n var datatype = item['@type'] || null;\n\n // convert to XSD datatypes as appropriate\n if(_isBoolean(value)) {\n object.value = value.toString();\n object.datatype = datatype || XSD_BOOLEAN;\n } else if(_isDouble(value) || datatype === XSD_DOUBLE) {\n if(!_isDouble(value)) {\n value = parseFloat(value);\n }\n // canonical double representation\n object.value = value.toExponential(15).replace(/(\\d)0*e\\+?/, '$1E');\n object.datatype = datatype || XSD_DOUBLE;\n } else if(_isNumber(value)) {\n object.value = value.toFixed(0);\n object.datatype = datatype || XSD_INTEGER;\n } else if('@language' in item) {\n object.value = value;\n object.datatype = datatype || RDF_LANGSTRING;\n object.language = item['@language'];\n } else {\n object.value = value;\n object.datatype = datatype || XSD_STRING;\n }\n } else {\n // convert string/node object to RDF\n var id = _isObject(item) ? item['@id'] : item;\n object.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';\n object.value = id;\n }\n\n // skip relative IRIs\n if(object.type === 'IRI' && !_isAbsoluteIri(object.value)) {\n return null;\n }\n\n return object;\n}\n\n/**\n * Converts an RDF triple object to a JSON-LD object.\n *\n * @param o the RDF triple object to convert.\n * @param useNativeTypes true to output native types, false not to.\n *\n * @return the JSON-LD object.\n */\nfunction _RDFToObject(o, useNativeTypes) {\n // convert IRI/blank node object to JSON-LD\n if(o.type === 'IRI' || o.type === 'blank node') {\n return {'@id': o.value};\n }\n\n // convert literal to JSON-LD\n var rval = {'@value': o.value};\n\n // add language\n if(o.language) {\n rval['@language'] = o.language;\n } else {\n var type = o.datatype;\n if(!type) {\n type = XSD_STRING;\n }\n // use native types for certain xsd types\n if(useNativeTypes) {\n if(type === XSD_BOOLEAN) {\n if(rval['@value'] === 'true') {\n rval['@value'] = true;\n } else if(rval['@value'] === 'false') {\n rval['@value'] = false;\n }\n } else if(_isNumeric(rval['@value'])) {\n if(type === XSD_INTEGER) {\n var i = parseInt(rval['@value'], 10);\n if(i.toFixed(0) === rval['@value']) {\n rval['@value'] = i;\n }\n } else if(type === XSD_DOUBLE) {\n rval['@value'] = parseFloat(rval['@value']);\n }\n }\n // do not add native type\n if([XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING]\n .indexOf(type) === -1) {\n rval['@type'] = type;\n }\n } else if(type !== XSD_STRING) {\n rval['@type'] = type;\n }\n }\n\n return rval;\n}\n\n/**\n * Compares two RDF triples for equality.\n *\n * @param t1 the first triple.\n * @param t2 the second triple.\n *\n * @return true if the triples are the same, false if not.\n */\nfunction _compareRDFTriples(t1, t2) {\n var attrs = ['subject', 'predicate', 'object'];\n for(var i = 0; i < attrs.length; ++i) {\n var attr = attrs[i];\n if(t1[attr].type !== t2[attr].type || t1[attr].value !== t2[attr].value) {\n return false;\n }\n }\n if(t1.object.language !== t2.object.language) {\n return false;\n }\n if(t1.object.datatype !== t2.object.datatype) {\n return false;\n }\n return true;\n}\n\n/////////////////////////////// DEFINE URDNA2015 //////////////////////////////\n\nvar URDNA2015 = (function() {\n\nvar POSITIONS = {'subject': 's', 'object': 'o', 'name': 'g'};\n\nvar Normalize = function(options) {\n options = options || {};\n this.name = 'URDNA2015';\n this.options = options;\n this.blankNodeInfo = {};\n this.hashToBlankNodes = {};\n this.canonicalIssuer = new IdentifierIssuer('_:c14n');\n this.quads = [];\n this.schedule = {};\n if('maxCallStackDepth' in options) {\n this.schedule.MAX_DEPTH = options.maxCallStackDepth;\n } else {\n this.schedule.MAX_DEPTH = 500;\n }\n if('maxTotalCallStackDepth' in options) {\n this.schedule.MAX_TOTAL_DEPTH = options.maxCallStackDepth;\n } else {\n this.schedule.MAX_TOTAL_DEPTH = 0xFFFFFFFF;\n }\n this.schedule.depth = 0;\n this.schedule.totalDepth = 0;\n if('timeSlice' in options) {\n this.schedule.timeSlice = options.timeSlice;\n } else {\n // milliseconds\n this.schedule.timeSlice = 10;\n }\n};\n\n// do some work in a time slice, but in serial\nNormalize.prototype.doWork = function(fn, callback) {\n var schedule = this.schedule;\n\n if(schedule.totalDepth >= schedule.MAX_TOTAL_DEPTH) {\n return callback(new Error(\n 'Maximum total call stack depth exceeded; normalization aborting.'));\n }\n\n (function work() {\n if(schedule.depth === schedule.MAX_DEPTH) {\n // stack too deep, run on next tick\n schedule.depth = 0;\n schedule.running = false;\n return jsonld.nextTick(work);\n }\n\n // if not yet running, force run\n var now = new Date().getTime();\n if(!schedule.running) {\n schedule.start = new Date().getTime();\n schedule.deadline = schedule.start + schedule.timeSlice;\n }\n\n // TODO: should also include an estimate of expectedWorkTime\n if(now < schedule.deadline) {\n schedule.running = true;\n schedule.depth++;\n schedule.totalDepth++;\n return fn(function(err, result) {\n schedule.depth--;\n schedule.totalDepth--;\n callback(err, result);\n });\n }\n\n // not enough time left in this slice, run after letting browser\n // do some other things\n schedule.depth = 0;\n schedule.running = false;\n jsonld.setImmediate(work);\n })();\n};\n\n// asynchronously loop\nNormalize.prototype.forEach = function(iterable, fn, callback) {\n var self = this;\n var iterator;\n var idx = 0;\n var length;\n if(_isArray(iterable)) {\n length = iterable.length;\n iterator = function() {\n if(idx === length) {\n return false;\n }\n iterator.value = iterable[idx++];\n iterator.key = idx;\n return true;\n };\n } else {\n var keys = Object.keys(iterable);\n length = keys.length;\n iterator = function() {\n if(idx === length) {\n return false;\n }\n iterator.key = keys[idx++];\n iterator.value = iterable[iterator.key];\n return true;\n };\n }\n\n (function iterate(err, result) {\n if(err) {\n return callback(err);\n }\n if(iterator()) {\n return self.doWork(function() {\n fn(iterator.value, iterator.key, iterate);\n });\n }\n callback();\n })();\n};\n\n// asynchronous waterfall\nNormalize.prototype.waterfall = function(fns, callback) {\n var self = this;\n self.forEach(fns, function(fn, idx, callback) {\n self.doWork(fn, callback);\n }, callback);\n};\n\n// asynchronous while\nNormalize.prototype.whilst = function(condition, fn, callback) {\n var self = this;\n (function loop(err) {\n if(err) {\n return callback(err);\n }\n if(!condition()) {\n return callback();\n }\n self.doWork(fn, loop);\n })();\n};\n\n// 4.4) Normalization Algorithm\nNormalize.prototype.main = function(dataset, callback) {\n var self = this;\n self.schedule.start = new Date().getTime();\n var result;\n\n // handle invalid output format\n if(self.options.format) {\n if(self.options.format !== 'application/nquads') {\n return callback(new JsonLdError(\n 'Unknown output format.',\n 'jsonld.UnknownFormat', {format: self.options.format}));\n }\n }\n\n // 1) Create the normalization state.\n\n // Note: Optimize by generating non-normalized blank node map concurrently.\n var nonNormalized = {};\n\n self.waterfall([\n function(callback) {\n // 2) For every quad in input dataset:\n self.forEach(dataset, function(triples, graphName, callback) {\n if(graphName === '@default') {\n graphName = null;\n }\n self.forEach(triples, function(quad, idx, callback) {\n if(graphName !== null) {\n if(graphName.indexOf('_:') === 0) {\n quad.name = {type: 'blank node', value: graphName};\n } else {\n quad.name = {type: 'IRI', value: graphName};\n }\n }\n self.quads.push(quad);\n\n // 2.1) For each blank node that occurs in the quad, add a reference\n // to the quad using the blank node identifier in the blank node to\n // quads map, creating a new entry if necessary.\n self.forEachComponent(quad, function(component) {\n if(component.type !== 'blank node') {\n return;\n }\n var id = component.value;\n if(id in self.blankNodeInfo) {\n self.blankNodeInfo[id].quads.push(quad);\n } else {\n nonNormalized[id] = true;\n self.blankNodeInfo[id] = {quads: [quad]};\n }\n });\n callback();\n }, callback);\n }, callback);\n },\n function(callback) {\n // 3) Create a list of non-normalized blank node identifiers\n // non-normalized identifiers and populate it using the keys from the\n // blank node to quads map.\n // Note: We use a map here and it was generated during step 2.\n\n // 4) Initialize simple, a boolean flag, to true.\n var simple = true;\n\n // 5) While simple is true, issue canonical identifiers for blank nodes:\n self.whilst(function() { return simple; }, function(callback) {\n // 5.1) Set simple to false.\n simple = false;\n\n // 5.2) Clear hash to blank nodes map.\n self.hashToBlankNodes = {};\n\n self.waterfall([\n function(callback) {\n // 5.3) For each blank node identifier identifier in non-normalized\n // identifiers:\n self.forEach(nonNormalized, function(value, id, callback) {\n // 5.3.1) Create a hash, hash, according to the Hash First Degree\n // Quads algorithm.\n self.hashFirstDegreeQuads(id, function(err, hash) {\n if(err) {\n return callback(err);\n }\n // 5.3.2) Add hash and identifier to hash to blank nodes map,\n // creating a new entry if necessary.\n if(hash in self.hashToBlankNodes) {\n self.hashToBlankNodes[hash].push(id);\n } else {\n self.hashToBlankNodes[hash] = [id];\n }\n callback();\n });\n }, callback);\n },\n function(callback) {\n // 5.4) For each hash to identifier list mapping in hash to blank\n // nodes map, lexicographically-sorted by hash:\n var hashes = Object.keys(self.hashToBlankNodes).sort();\n self.forEach(hashes, function(hash, i, callback) {\n // 5.4.1) If the length of identifier list is greater than 1,\n // continue to the next mapping.\n var idList = self.hashToBlankNodes[hash];\n if(idList.length > 1) {\n return callback();\n }\n\n // 5.4.2) Use the Issue Identifier algorithm, passing canonical\n // issuer and the single blank node identifier in identifier\n // list, identifier, to issue a canonical replacement identifier\n // for identifier.\n // TODO: consider changing `getId` to `issue`\n var id = idList[0];\n self.canonicalIssuer.getId(id);\n\n // 5.4.3) Remove identifier from non-normalized identifiers.\n delete nonNormalized[id];\n\n // 5.4.4) Remove hash from the hash to blank nodes map.\n delete self.hashToBlankNodes[hash];\n\n // 5.4.5) Set simple to true.\n simple = true;\n callback();\n }, callback);\n }\n ], callback);\n }, callback);\n },\n function(callback) {\n // 6) For each hash to identifier list mapping in hash to blank nodes map,\n // lexicographically-sorted by hash:\n var hashes = Object.keys(self.hashToBlankNodes).sort();\n self.forEach(hashes, function(hash, idx, callback) {\n // 6.1) Create hash path list where each item will be a result of\n // running the Hash N-Degree Quads algorithm.\n var hashPathList = [];\n\n // 6.2) For each blank node identifier identifier in identifier list:\n var idList = self.hashToBlankNodes[hash];\n self.waterfall([\n function(callback) {\n self.forEach(idList, function(id, idx, callback) {\n // 6.2.1) If a canonical identifier has already been issued for\n // identifier, continue to the next identifier.\n if(self.canonicalIssuer.hasId(id)) {\n return callback();\n }\n\n // 6.2.2) Create temporary issuer, an identifier issuer\n // initialized with the prefix _:b.\n var issuer = new IdentifierIssuer('_:b');\n\n // 6.2.3) Use the Issue Identifier algorithm, passing temporary\n // issuer and identifier, to issue a new temporary blank node\n // identifier for identifier.\n issuer.getId(id);\n\n // 6.2.4) Run the Hash N-Degree Quads algorithm, passing\n // temporary issuer, and append the result to the hash path list.\n self.hashNDegreeQuads(id, issuer, function(err, result) {\n if(err) {\n return callback(err);\n }\n hashPathList.push(result);\n callback();\n });\n }, callback);\n },\n function(callback) {\n // 6.3) For each result in the hash path list,\n // lexicographically-sorted by the hash in result:\n hashPathList.sort(function(a, b) {\n return (a.hash < b.hash) ? -1 : ((a.hash > b.hash) ? 1 : 0);\n });\n self.forEach(hashPathList, function(result, idx, callback) {\n // 6.3.1) For each blank node identifier, existing identifier,\n // that was issued a temporary identifier by identifier issuer\n // in result, issue a canonical identifier, in the same order,\n // using the Issue Identifier algorithm, passing canonical\n // issuer and existing identifier.\n for(var existing in result.issuer.existing) {\n self.canonicalIssuer.getId(existing);\n }\n callback();\n }, callback);\n }\n ], callback);\n }, callback);\n }, function(callback) {\n /* Note: At this point all blank nodes in the set of RDF quads have been\n assigned canonical identifiers, which have been stored in the canonical\n issuer. Here each quad is updated by assigning each of its blank nodes\n its new identifier. */\n\n // 7) For each quad, quad, in input dataset:\n var normalized = [];\n self.waterfall([\n function(callback) {\n self.forEach(self.quads, function(quad, idx, callback) {\n // 7.1) Create a copy, quad copy, of quad and replace any existing\n // blank node identifiers using the canonical identifiers\n // previously issued by canonical issuer.\n // Note: We optimize away the copy here.\n self.forEachComponent(quad, function(component) {\n if(component.type === 'blank node' &&\n component.value.indexOf(self.canonicalIssuer.prefix) !== 0) {\n component.value = self.canonicalIssuer.getId(component.value);\n }\n });\n // 7.2) Add quad copy to the normalized dataset.\n normalized.push(_toNQuad(quad));\n callback();\n }, callback);\n },\n function(callback) {\n // sort normalized output\n normalized.sort();\n\n // 8) Return the normalized dataset.\n if(self.options.format === 'application/nquads') {\n result = normalized.join('');\n return callback();\n }\n\n result = _parseNQuads(normalized.join(''));\n callback();\n }\n ], callback);\n }\n ], function(err) {\n callback(err, result);\n });\n};\n\n// 4.6) Hash First Degree Quads\nNormalize.prototype.hashFirstDegreeQuads = function(id, callback) {\n var self = this;\n\n // return cached hash\n var info = self.blankNodeInfo[id];\n if('hash' in info) {\n return callback(null, info.hash);\n }\n\n // 1) Initialize nquads to an empty list. It will be used to store quads in\n // N-Quads format.\n var nquads = [];\n\n // 2) Get the list of quads quads associated with the reference blank node\n // identifier in the blank node to quads map.\n var quads = info.quads;\n\n // 3) For each quad quad in quads:\n self.forEach(quads, function(quad, idx, callback) {\n // 3.1) Serialize the quad in N-Quads format with the following special\n // rule:\n\n // 3.1.1) If any component in quad is an blank node, then serialize it\n // using a special identifier as follows:\n var copy = {predicate: quad.predicate};\n self.forEachComponent(quad, function(component, key) {\n // 3.1.2) If the blank node's existing blank node identifier matches the\n // reference blank node identifier then use the blank node identifier _:a,\n // otherwise, use the blank node identifier _:z.\n copy[key] = self.modifyFirstDegreeComponent(id, component, key);\n });\n nquads.push(_toNQuad(copy));\n callback();\n }, function(err) {\n if(err) {\n return callback(err);\n }\n // 4) Sort nquads in lexicographical order.\n nquads.sort();\n\n // 5) Return the hash that results from passing the sorted, joined nquads\n // through the hash algorithm.\n info.hash = NormalizeHash.hashNQuads(self.name, nquads);\n callback(null, info.hash);\n });\n};\n\n// helper for modifying component during Hash First Degree Quads\nNormalize.prototype.modifyFirstDegreeComponent = function(id, component) {\n if(component.type !== 'blank node') {\n return component;\n }\n component = _clone(component);\n component.value = (component.value === id ? '_:a' : '_:z');\n return component;\n};\n\n// 4.7) Hash Related Blank Node\nNormalize.prototype.hashRelatedBlankNode = function(\n related, quad, issuer, position, callback) {\n var self = this;\n\n // 1) Set the identifier to use for related, preferring first the canonical\n // identifier for related if issued, second the identifier issued by issuer\n // if issued, and last, if necessary, the result of the Hash First Degree\n // Quads algorithm, passing related.\n var id;\n self.waterfall([\n function(callback) {\n if(self.canonicalIssuer.hasId(related)) {\n id = self.canonicalIssuer.getId(related);\n return callback();\n }\n if(issuer.hasId(related)) {\n id = issuer.getId(related);\n return callback();\n }\n self.hashFirstDegreeQuads(related, function(err, hash) {\n if(err) {\n return callback(err);\n }\n id = hash;\n callback();\n });\n }\n ], function(err) {\n if(err) {\n return callback(err);\n }\n\n // 2) Initialize a string input to the value of position.\n // Note: We use a hash object instead.\n var md = new NormalizeHash(self.name);\n md.update(position);\n\n // 3) If position is not g, append <, the value of the predicate in quad,\n // and > to input.\n if(position !== 'g') {\n md.update(self.getRelatedPredicate(quad));\n }\n\n // 4) Append identifier to input.\n md.update(id);\n\n // 5) Return the hash that results from passing input through the hash\n // algorithm.\n return callback(null, md.digest());\n });\n};\n\n// helper for getting a related predicate\nNormalize.prototype.getRelatedPredicate = function(quad) {\n return '<' + quad.predicate.value + '>';\n};\n\n// 4.8) Hash N-Degree Quads\nNormalize.prototype.hashNDegreeQuads = function(id, issuer, callback) {\n var self = this;\n\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n // Note: 2) and 3) handled within `createHashToRelated`\n var hashToRelated;\n var md = new NormalizeHash(self.name);\n self.waterfall([\n function(callback) {\n self.createHashToRelated(id, issuer, function(err, result) {\n if(err) {\n return callback(err);\n }\n hashToRelated = result;\n callback();\n });\n },\n function(callback) {\n // 4) Create an empty string, data to hash.\n // Note: We created a hash object `md` above instead.\n\n // 5) For each related hash to blank node list mapping in hash to related\n // blank nodes map, sorted lexicographically by related hash:\n var hashes = Object.keys(hashToRelated).sort();\n self.forEach(hashes, function(hash, idx, callback) {\n // 5.1) Append the related hash to the data to hash.\n md.update(hash);\n\n // 5.2) Create a string chosen path.\n var chosenPath = '';\n\n // 5.3) Create an unset chosen issuer variable.\n var chosenIssuer;\n\n // 5.4) For each permutation of blank node list:\n var permutator = new Permutator(hashToRelated[hash]);\n self.whilst(\n function() { return permutator.hasNext(); },\n function(nextPermutation) {\n var permutation = permutator.next();\n\n // 5.4.1) Create a copy of issuer, issuer copy.\n var issuerCopy = issuer.clone();\n\n // 5.4.2) Create a string path.\n var path = '';\n\n // 5.4.3) Create a recursion list, to store blank node identifiers\n // that must be recursively processed by this algorithm.\n var recursionList = [];\n\n self.waterfall([\n function(callback) {\n // 5.4.4) For each related in permutation:\n self.forEach(permutation, function(related, idx, callback) {\n // 5.4.4.1) If a canonical identifier has been issued for\n // related, append it to path.\n if(self.canonicalIssuer.hasId(related)) {\n path += self.canonicalIssuer.getId(related);\n } else {\n // 5.4.4.2) Otherwise:\n // 5.4.4.2.1) If issuer copy has not issued an identifier for\n // related, append related to recursion list.\n if(!issuerCopy.hasId(related)) {\n recursionList.push(related);\n }\n // 5.4.4.2.2) Use the Issue Identifier algorithm, passing\n // issuer copy and related and append the result to path.\n path += issuerCopy.getId(related);\n }\n\n // 5.4.4.3) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n if(chosenPath.length !== 0 &&\n path.length >= chosenPath.length && path > chosenPath) {\n // FIXME: may cause inaccurate total depth calculation\n return nextPermutation();\n }\n callback();\n }, callback);\n },\n function(callback) {\n // 5.4.5) For each related in recursion list:\n self.forEach(recursionList, function(related, idx, callback) {\n // 5.4.5.1) Set result to the result of recursively executing\n // the Hash N-Degree Quads algorithm, passing related for\n // identifier and issuer copy for path identifier issuer.\n self.hashNDegreeQuads(\n related, issuerCopy, function(err, result) {\n if(err) {\n return callback(err);\n }\n\n // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer\n // copy and related and append the result to path.\n path += issuerCopy.getId(related);\n\n // 5.4.5.3) Append <, the hash in result, and > to path.\n path += '<' + result.hash + '>';\n\n // 5.4.5.4) Set issuer copy to the identifier issuer in\n // result.\n issuerCopy = result.issuer;\n\n // 5.4.5.5) If chosen path is not empty and the length of path\n // is greater than or equal to the length of chosen path and\n // path is lexicographically greater than chosen path, then\n // skip to the next permutation.\n if(chosenPath.length !== 0 &&\n path.length >= chosenPath.length && path > chosenPath) {\n // FIXME: may cause inaccurate total depth calculation\n return nextPermutation();\n }\n callback();\n });\n }, callback);\n },\n function(callback) {\n // 5.4.6) If chosen path is empty or path is lexicographically\n // less than chosen path, set chosen path to path and chosen\n // issuer to issuer copy.\n if(chosenPath.length === 0 || path < chosenPath) {\n chosenPath = path;\n chosenIssuer = issuerCopy;\n }\n callback();\n }\n ], nextPermutation);\n }, function(err) {\n if(err) {\n return callback(err);\n }\n\n // 5.5) Append chosen path to data to hash.\n md.update(chosenPath);\n\n // 5.6) Replace issuer, by reference, with chosen issuer.\n issuer = chosenIssuer;\n callback();\n });\n }, callback);\n }\n ], function(err) {\n // 6) Return issuer and the hash that results from passing data to hash\n // through the hash algorithm.\n callback(err, {hash: md.digest(), issuer: issuer});\n });\n};\n\n// helper for creating hash to related blank nodes map\nNormalize.prototype.createHashToRelated = function(id, issuer, callback) {\n var self = this;\n\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n var hashToRelated = {};\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n var quads = self.blankNodeInfo[id].quads;\n\n // 3) For each quad in quads:\n self.forEach(quads, function(quad, idx, callback) {\n // 3.1) For each component in quad, if component is the subject, object,\n // and graph name and it is a blank node that is not identified by\n // identifier:\n self.forEach(quad, function(component, key, callback) {\n if(key === 'predicate' ||\n !(component.type === 'blank node' && component.value !== id)) {\n return callback();\n }\n // 3.1.1) Set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for component as\n // related, quad, path identifier issuer as issuer, and position as\n // either s, o, or g based on whether component is a subject, object,\n // graph name, respectively.\n var related = component.value;\n var position = POSITIONS[key];\n self.hashRelatedBlankNode(\n related, quad, issuer, position, function(err, hash) {\n if(err) {\n return callback(err);\n }\n // 3.1.2) Add a mapping of hash to the blank node identifier for\n // component to hash to related blank nodes map, adding an entry as\n // necessary.\n if(hash in hashToRelated) {\n hashToRelated[hash].push(related);\n } else {\n hashToRelated[hash] = [related];\n }\n callback();\n });\n }, callback);\n }, function(err) {\n callback(err, hashToRelated);\n });\n};\n\n// helper that iterates over quad components (skips predicate)\nNormalize.prototype.forEachComponent = function(quad, op) {\n for(var key in quad) {\n // skip `predicate`\n if(key === 'predicate') {\n continue;\n }\n op(quad[key], key, quad);\n }\n};\n\nreturn Normalize;\n\n})(); // end of define URDNA2015\n\n/////////////////////////////// DEFINE URGNA2012 //////////////////////////////\n\nvar URGNA2012 = (function() {\n\nvar Normalize = function(options) {\n URDNA2015.call(this, options);\n this.name = 'URGNA2012';\n};\nNormalize.prototype = new URDNA2015();\n\n// helper for modifying component during Hash First Degree Quads\nNormalize.prototype.modifyFirstDegreeComponent = function(id, component, key) {\n if(component.type !== 'blank node') {\n return component;\n }\n component = _clone(component);\n if(key === 'name') {\n component.value = '_:g';\n } else {\n component.value = (component.value === id ? '_:a' : '_:z');\n }\n return component;\n};\n\n// helper for getting a related predicate\nNormalize.prototype.getRelatedPredicate = function(quad) {\n return quad.predicate.value;\n};\n\n// helper for creating hash to related blank nodes map\nNormalize.prototype.createHashToRelated = function(id, issuer, callback) {\n var self = this;\n\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n var hashToRelated = {};\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n var quads = self.blankNodeInfo[id].quads;\n\n // 3) For each quad in quads:\n self.forEach(quads, function(quad, idx, callback) {\n // 3.1) If the quad's subject is a blank node that does not match\n // identifier, set hash to the result of the Hash Related Blank Node\n // algorithm, passing the blank node identifier for subject as related,\n // quad, path identifier issuer as issuer, and p as position.\n var position;\n var related;\n if(quad.subject.type === 'blank node' && quad.subject.value !== id) {\n related = quad.subject.value;\n position = 'p';\n } else if(quad.object.type === 'blank node' && quad.object.value !== id) {\n // 3.2) Otherwise, if quad's object is a blank node that does not match\n // identifier, to the result of the Hash Related Blank Node algorithm,\n // passing the blank node identifier for object as related, quad, path\n // identifier issuer as issuer, and r as position.\n related = quad.object.value;\n position = 'r';\n } else {\n // 3.3) Otherwise, continue to the next quad.\n return callback();\n }\n // 3.4) Add a mapping of hash to the blank node identifier for the\n // component that matched (subject or object) to hash to related blank\n // nodes map, adding an entry as necessary.\n self.hashRelatedBlankNode(\n related, quad, issuer, position, function(err, hash) {\n if(hash in hashToRelated) {\n hashToRelated[hash].push(related);\n } else {\n hashToRelated[hash] = [related];\n }\n callback();\n });\n }, function(err) {\n callback(err, hashToRelated);\n });\n};\n\nreturn Normalize;\n\n})(); // end of define URGNA2012\n\n/**\n * Recursively flattens the subjects in the given JSON-LD expanded input\n * into a node map.\n *\n * @param input the JSON-LD expanded input.\n * @param graphs a map of graph name to subject map.\n * @param graph the name of the current graph.\n * @param issuer the blank node identifier issuer.\n * @param name the name assigned to the current input if it is a bnode.\n * @param list the list to append to, null for none.\n */\nfunction _createNodeMap(input, graphs, graph, issuer, name, list) {\n // recurse through array\n if(_isArray(input)) {\n for(var i = 0; i < input.length; ++i) {\n _createNodeMap(input[i], graphs, graph, issuer, undefined, list);\n }\n return;\n }\n\n // add non-object to list\n if(!_isObject(input)) {\n if(list) {\n list.push(input);\n }\n return;\n }\n\n // add values to list\n if(_isValue(input)) {\n if('@type' in input) {\n var type = input['@type'];\n // rename @type blank node\n if(type.indexOf('_:') === 0) {\n input['@type'] = type = issuer.getId(type);\n }\n }\n if(list) {\n list.push(input);\n }\n return;\n }\n\n // Note: At this point, input must be a subject.\n\n // spec requires @type to be named first, so assign names early\n if('@type' in input) {\n var types = input['@type'];\n for(var i = 0; i < types.length; ++i) {\n var type = types[i];\n if(type.indexOf('_:') === 0) {\n issuer.getId(type);\n }\n }\n }\n\n // get name for subject\n if(_isUndefined(name)) {\n name = _isBlankNode(input) ? issuer.getId(input['@id']) : input['@id'];\n }\n\n // add subject reference to list\n if(list) {\n list.push({'@id': name});\n }\n\n // create new subject or merge into existing one\n var subjects = graphs[graph];\n var subject = subjects[name] = subjects[name] || {};\n subject['@id'] = name;\n var properties = Object.keys(input).sort();\n for(var pi = 0; pi < properties.length; ++pi) {\n var property = properties[pi];\n\n // skip @id\n if(property === '@id') {\n continue;\n }\n\n // handle reverse properties\n if(property === '@reverse') {\n var referencedNode = {'@id': name};\n var reverseMap = input['@reverse'];\n for(var reverseProperty in reverseMap) {\n var items = reverseMap[reverseProperty];\n for(var ii = 0; ii < items.length; ++ii) {\n var item = items[ii];\n var itemName = item['@id'];\n if(_isBlankNode(item)) {\n itemName = issuer.getId(itemName);\n }\n _createNodeMap(item, graphs, graph, issuer, itemName);\n jsonld.addValue(\n subjects[itemName], reverseProperty, referencedNode,\n {propertyIsArray: true, allowDuplicate: false});\n }\n }\n continue;\n }\n\n // recurse into graph\n if(property === '@graph') {\n // add graph subjects map entry\n if(!(name in graphs)) {\n graphs[name] = {};\n }\n var g = (graph === '@merged') ? graph : name;\n _createNodeMap(input[property], graphs, g, issuer);\n continue;\n }\n\n // copy non-@type keywords\n if(property !== '@type' && _isKeyword(property)) {\n if(property === '@index' && property in subject &&\n (input[property] !== subject[property] ||\n input[property]['@id'] !== subject[property]['@id'])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; conflicting @index property detected.',\n 'jsonld.SyntaxError',\n {code: 'conflicting indexes', subject: subject});\n }\n subject[property] = input[property];\n continue;\n }\n\n // iterate over objects\n var objects = input[property];\n\n // if property is a bnode, assign it a new id\n if(property.indexOf('_:') === 0) {\n property = issuer.getId(property);\n }\n\n // ensure property is added for empty arrays\n if(objects.length === 0) {\n jsonld.addValue(subject, property, [], {propertyIsArray: true});\n continue;\n }\n for(var oi = 0; oi < objects.length; ++oi) {\n var o = objects[oi];\n\n if(property === '@type') {\n // rename @type blank nodes\n o = (o.indexOf('_:') === 0) ? issuer.getId(o) : o;\n }\n\n // handle embedded subject or subject reference\n if(_isSubject(o) || _isSubjectReference(o)) {\n // relabel blank node @id\n var id = _isBlankNode(o) ? issuer.getId(o['@id']) : o['@id'];\n\n // add reference and recurse\n jsonld.addValue(\n subject, property, {'@id': id},\n {propertyIsArray: true, allowDuplicate: false});\n _createNodeMap(o, graphs, graph, issuer, id);\n } else if(_isList(o)) {\n // handle @list\n var _list = [];\n _createNodeMap(o['@list'], graphs, graph, issuer, name, _list);\n o = {'@list': _list};\n jsonld.addValue(\n subject, property, o,\n {propertyIsArray: true, allowDuplicate: false});\n } else {\n // handle @value\n _createNodeMap(o, graphs, graph, issuer, name);\n jsonld.addValue(\n subject, property, o, {propertyIsArray: true, allowDuplicate: false});\n }\n }\n }\n}\n\nfunction _mergeNodeMaps(graphs) {\n // add all non-default graphs to default graph\n var defaultGraph = graphs['@default'];\n var graphNames = Object.keys(graphs).sort();\n for(var i = 0; i < graphNames.length; ++i) {\n var graphName = graphNames[i];\n if(graphName === '@default') {\n continue;\n }\n var nodeMap = graphs[graphName];\n var subject = defaultGraph[graphName];\n if(!subject) {\n defaultGraph[graphName] = subject = {\n '@id': graphName,\n '@graph': []\n };\n } else if(!('@graph' in subject)) {\n subject['@graph'] = [];\n }\n var graph = subject['@graph'];\n var ids = Object.keys(nodeMap).sort();\n for(var ii = 0; ii < ids.length; ++ii) {\n var node = nodeMap[ids[ii]];\n // only add full subjects\n if(!_isSubjectReference(node)) {\n graph.push(node);\n }\n }\n }\n return defaultGraph;\n}\n\n/**\n * Frames subjects according to the given frame.\n *\n * @param state the current framing state.\n * @param subjects the subjects to filter.\n * @param frame the frame.\n * @param parent the parent subject or top-level array.\n * @param property the parent property, initialized to null.\n */\nfunction _frame(state, subjects, frame, parent, property) {\n // validate the frame\n _validateFrame(frame);\n frame = frame[0];\n\n // get flags for current frame\n var options = state.options;\n var flags = {\n embed: _getFrameFlag(frame, options, 'embed'),\n explicit: _getFrameFlag(frame, options, 'explicit'),\n requireAll: _getFrameFlag(frame, options, 'requireAll')\n };\n\n // filter out subjects that match the frame\n var matches = _filterSubjects(state, subjects, frame, flags);\n\n // add matches to output\n var ids = Object.keys(matches).sort();\n for(var idx = 0; idx < ids.length; ++idx) {\n var id = ids[idx];\n var subject = matches[id];\n\n if(flags.embed === '@link' && id in state.link) {\n // TODO: may want to also match an existing linked subject against\n // the current frame ... so different frames could produce different\n // subjects that are only shared in-memory when the frames are the same\n\n // add existing linked subject\n _addFrameOutput(parent, property, state.link[id]);\n continue;\n }\n\n /* Note: In order to treat each top-level match as a compartmentalized\n result, clear the unique embedded subjects map when the property is null,\n which only occurs at the top-level. */\n if(property === null) {\n state.uniqueEmbeds = {};\n }\n\n // start output for subject\n var output = {};\n output['@id'] = id;\n state.link[id] = output;\n\n // if embed is @never or if a circular reference would be created by an\n // embed, the subject cannot be embedded, just add the reference;\n // note that a circular reference won't occur when the embed flag is\n // `@link` as the above check will short-circuit before reaching this point\n if(flags.embed === '@never' ||\n _createsCircularReference(subject, state.subjectStack)) {\n _addFrameOutput(parent, property, output);\n continue;\n }\n\n // if only the last match should be embedded\n if(flags.embed === '@last') {\n // remove any existing embed\n if(id in state.uniqueEmbeds) {\n _removeEmbed(state, id);\n }\n state.uniqueEmbeds[id] = {parent: parent, property: property};\n }\n\n // push matching subject onto stack to enable circular embed checks\n state.subjectStack.push(subject);\n\n // iterate over subject properties\n var props = Object.keys(subject).sort();\n for(var i = 0; i < props.length; i++) {\n var prop = props[i];\n\n // copy keywords to output\n if(_isKeyword(prop)) {\n output[prop] = _clone(subject[prop]);\n continue;\n }\n\n // explicit is on and property isn't in the frame, skip processing\n if(flags.explicit && !(prop in frame)) {\n continue;\n }\n\n // add objects\n var objects = subject[prop];\n for(var oi = 0; oi < objects.length; ++oi) {\n var o = objects[oi];\n\n // recurse into list\n if(_isList(o)) {\n // add empty list\n var list = {'@list': []};\n _addFrameOutput(output, prop, list);\n\n // add list objects\n var src = o['@list'];\n for(var n in src) {\n o = src[n];\n if(_isSubjectReference(o)) {\n var subframe = (prop in frame ?\n frame[prop][0]['@list'] : _createImplicitFrame(flags));\n // recurse into subject reference\n _frame(state, [o['@id']], subframe, list, '@list');\n } else {\n // include other values automatically\n _addFrameOutput(list, '@list', _clone(o));\n }\n }\n continue;\n }\n\n if(_isSubjectReference(o)) {\n // recurse into subject reference\n var subframe = (prop in frame ?\n frame[prop] : _createImplicitFrame(flags));\n _frame(state, [o['@id']], subframe, output, prop);\n } else {\n // include other values automatically\n _addFrameOutput(output, prop, _clone(o));\n }\n }\n }\n\n // handle defaults\n var props = Object.keys(frame).sort();\n for(var i = 0; i < props.length; ++i) {\n var prop = props[i];\n\n // skip keywords\n if(_isKeyword(prop)) {\n continue;\n }\n\n // if omit default is off, then include default values for properties\n // that appear in the next frame but are not in the matching subject\n var next = frame[prop][0];\n var omitDefaultOn = _getFrameFlag(next, options, 'omitDefault');\n if(!omitDefaultOn && !(prop in output)) {\n var preserve = '@null';\n if('@default' in next) {\n preserve = _clone(next['@default']);\n }\n if(!_isArray(preserve)) {\n preserve = [preserve];\n }\n output[prop] = [{'@preserve': preserve}];\n }\n }\n\n // add output to parent\n _addFrameOutput(parent, property, output);\n\n // pop matching subject from circular ref-checking stack\n state.subjectStack.pop();\n }\n}\n\n/**\n * Creates an implicit frame when recursing through subject matches. If\n * a frame doesn't have an explicit frame for a particular property, then\n * a wildcard child frame will be created that uses the same flags that the\n * parent frame used.\n *\n * @param flags the current framing flags.\n *\n * @return the implicit frame.\n */\nfunction _createImplicitFrame(flags) {\n var frame = {};\n for(var key in flags) {\n if(flags[key] !== undefined) {\n frame['@' + key] = [flags[key]];\n }\n }\n return [frame];\n}\n\n/**\n * Checks the current subject stack to see if embedding the given subject\n * would cause a circular reference.\n *\n * @param subjectToEmbed the subject to embed.\n * @param subjectStack the current stack of subjects.\n *\n * @return true if a circular reference would be created, false if not.\n */\nfunction _createsCircularReference(subjectToEmbed, subjectStack) {\n for(var i = subjectStack.length - 1; i >= 0; --i) {\n if(subjectStack[i]['@id'] === subjectToEmbed['@id']) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Gets the frame flag value for the given flag name.\n *\n * @param frame the frame.\n * @param options the framing options.\n * @param name the flag name.\n *\n * @return the flag value.\n */\nfunction _getFrameFlag(frame, options, name) {\n var flag = '@' + name;\n var rval = (flag in frame ? frame[flag][0] : options[name]);\n if(name === 'embed') {\n // default is \"@last\"\n // backwards-compatibility support for \"embed\" maps:\n // true => \"@last\"\n // false => \"@never\"\n if(rval === true) {\n rval = '@last';\n } else if(rval === false) {\n rval = '@never';\n } else if(rval !== '@always' && rval !== '@never' && rval !== '@link') {\n rval = '@last';\n }\n }\n return rval;\n}\n\n/**\n * Validates a JSON-LD frame, throwing an exception if the frame is invalid.\n *\n * @param frame the frame to validate.\n */\nfunction _validateFrame(frame) {\n if(!_isArray(frame) || frame.length !== 1 || !_isObject(frame[0])) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',\n 'jsonld.SyntaxError', {frame: frame});\n }\n}\n\n/**\n * Returns a map of all of the subjects that match a parsed frame.\n *\n * @param state the current framing state.\n * @param subjects the set of subjects to filter.\n * @param frame the parsed frame.\n * @param flags the frame flags.\n *\n * @return all of the matched subjects.\n */\nfunction _filterSubjects(state, subjects, frame, flags) {\n // filter subjects in @id order\n var rval = {};\n for(var i = 0; i < subjects.length; ++i) {\n var id = subjects[i];\n var subject = state.subjects[id];\n if(_filterSubject(subject, frame, flags)) {\n rval[id] = subject;\n }\n }\n return rval;\n}\n\n/**\n * Returns true if the given subject matches the given frame.\n *\n * @param subject the subject to check.\n * @param frame the frame to check.\n * @param flags the frame flags.\n *\n * @return true if the subject matches, false if not.\n */\nfunction _filterSubject(subject, frame, flags) {\n // check @type (object value means 'any' type, fall through to ducktyping)\n if('@type' in frame &&\n !(frame['@type'].length === 1 && _isObject(frame['@type'][0]))) {\n var types = frame['@type'];\n for(var i = 0; i < types.length; ++i) {\n // any matching @type is a match\n if(jsonld.hasValue(subject, '@type', types[i])) {\n return true;\n }\n }\n return false;\n }\n\n // check ducktype\n var wildcard = true;\n var matchesSome = false;\n for(var key in frame) {\n if(_isKeyword(key)) {\n // skip non-@id and non-@type\n if(key !== '@id' && key !== '@type') {\n continue;\n }\n wildcard = false;\n\n // check @id for a specific @id value\n if(key === '@id' && _isString(frame[key])) {\n if(subject[key] !== frame[key]) {\n return false;\n }\n matchesSome = true;\n continue;\n }\n }\n\n wildcard = false;\n\n if(key in subject) {\n // frame[key] === [] means do not match if property is present\n if(_isArray(frame[key]) && frame[key].length === 0 &&\n subject[key] !== undefined) {\n return false;\n }\n matchesSome = true;\n continue;\n }\n\n // all properties must match to be a duck unless a @default is specified\n var hasDefault = (_isArray(frame[key]) && _isObject(frame[key][0]) &&\n '@default' in frame[key][0]);\n if(flags.requireAll && !hasDefault) {\n return false;\n }\n }\n\n // return true if wildcard or subject matches some properties\n return wildcard || matchesSome;\n}\n\n/**\n * Removes an existing embed.\n *\n * @param state the current framing state.\n * @param id the @id of the embed to remove.\n */\nfunction _removeEmbed(state, id) {\n // get existing embed\n var embeds = state.uniqueEmbeds;\n var embed = embeds[id];\n var parent = embed.parent;\n var property = embed.property;\n\n // create reference to replace embed\n var subject = {'@id': id};\n\n // remove existing embed\n if(_isArray(parent)) {\n // replace subject with reference\n for(var i = 0; i < parent.length; ++i) {\n if(jsonld.compareValues(parent[i], subject)) {\n parent[i] = subject;\n break;\n }\n }\n } else {\n // replace subject with reference\n var useArray = _isArray(parent[property]);\n jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray});\n jsonld.addValue(parent, property, subject, {propertyIsArray: useArray});\n }\n\n // recursively remove dependent dangling embeds\n var removeDependents = function(id) {\n // get embed keys as a separate array to enable deleting keys in map\n var ids = Object.keys(embeds);\n for(var i = 0; i < ids.length; ++i) {\n var next = ids[i];\n if(next in embeds && _isObject(embeds[next].parent) &&\n embeds[next].parent['@id'] === id) {\n delete embeds[next];\n removeDependents(next);\n }\n }\n };\n removeDependents(id);\n}\n\n/**\n * Adds framing output to the given parent.\n *\n * @param parent the parent to add to.\n * @param property the parent property.\n * @param output the output to add.\n */\nfunction _addFrameOutput(parent, property, output) {\n if(_isObject(parent)) {\n jsonld.addValue(parent, property, output, {propertyIsArray: true});\n } else {\n parent.push(output);\n }\n}\n\n/**\n * Removes the @preserve keywords as the last step of the framing algorithm.\n *\n * @param ctx the active context used to compact the input.\n * @param input the framed, compacted output.\n * @param options the compaction options used.\n *\n * @return the resulting output.\n */\nfunction _removePreserve(ctx, input, options) {\n // recurse through arrays\n if(_isArray(input)) {\n var output = [];\n for(var i = 0; i < input.length; ++i) {\n var result = _removePreserve(ctx, input[i], options);\n // drop nulls from arrays\n if(result !== null) {\n output.push(result);\n }\n }\n input = output;\n } else if(_isObject(input)) {\n // remove @preserve\n if('@preserve' in input) {\n if(input['@preserve'] === '@null') {\n return null;\n }\n return input['@preserve'];\n }\n\n // skip @values\n if(_isValue(input)) {\n return input;\n }\n\n // recurse through @lists\n if(_isList(input)) {\n input['@list'] = _removePreserve(ctx, input['@list'], options);\n return input;\n }\n\n // handle in-memory linked nodes\n var idAlias = _compactIri(ctx, '@id');\n if(idAlias in input) {\n var id = input[idAlias];\n if(id in options.link) {\n var idx = options.link[id].indexOf(input);\n if(idx === -1) {\n // prevent circular visitation\n options.link[id].push(input);\n } else {\n // already visited\n return options.link[id][idx];\n }\n } else {\n // prevent circular visitation\n options.link[id] = [input];\n }\n }\n\n // recurse through properties\n for(var prop in input) {\n var result = _removePreserve(ctx, input[prop], options);\n var container = jsonld.getContextValue(ctx, prop, '@container');\n if(options.compactArrays && _isArray(result) && result.length === 1 &&\n container === null) {\n result = result[0];\n }\n input[prop] = result;\n }\n }\n return input;\n}\n\n/**\n * Compares two strings first based on length and then lexicographically.\n *\n * @param a the first string.\n * @param b the second string.\n *\n * @return -1 if a < b, 1 if a > b, 0 if a == b.\n */\nfunction _compareShortestLeast(a, b) {\n if(a.length < b.length) {\n return -1;\n }\n if(b.length < a.length) {\n return 1;\n }\n if(a === b) {\n return 0;\n }\n return (a < b) ? -1 : 1;\n}\n\n/**\n * Picks the preferred compaction term from the given inverse context entry.\n *\n * @param activeCtx the active context.\n * @param iri the IRI to pick the term for.\n * @param value the value to pick the term for.\n * @param containers the preferred containers.\n * @param typeOrLanguage either '@type' or '@language'.\n * @param typeOrLanguageValue the preferred value for '@type' or '@language'.\n *\n * @return the preferred term.\n */\nfunction _selectTerm(\n activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {\n if(typeOrLanguageValue === null) {\n typeOrLanguageValue = '@null';\n }\n\n // preferences for the value of @type or @language\n var prefs = [];\n\n // determine prefs for @id based on whether or not value compacts to a term\n if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') &&\n _isSubjectReference(value)) {\n // prefer @reverse first\n if(typeOrLanguageValue === '@reverse') {\n prefs.push('@reverse');\n }\n // try to compact value to a term\n var term = _compactIri(activeCtx, value['@id'], null, {vocab: true});\n if(term in activeCtx.mappings &&\n activeCtx.mappings[term] &&\n activeCtx.mappings[term]['@id'] === value['@id']) {\n // prefer @vocab\n prefs.push.apply(prefs, ['@vocab', '@id']);\n } else {\n // prefer @id\n prefs.push.apply(prefs, ['@id', '@vocab']);\n }\n } else {\n prefs.push(typeOrLanguageValue);\n }\n prefs.push('@none');\n\n var containerMap = activeCtx.inverse[iri];\n for(var ci = 0; ci < containers.length; ++ci) {\n // if container not available in the map, continue\n var container = containers[ci];\n if(!(container in containerMap)) {\n continue;\n }\n\n var typeOrLanguageValueMap = containerMap[container][typeOrLanguage];\n for(var pi = 0; pi < prefs.length; ++pi) {\n // if type/language option not available in the map, continue\n var pref = prefs[pi];\n if(!(pref in typeOrLanguageValueMap)) {\n continue;\n }\n\n // select term\n return typeOrLanguageValueMap[pref];\n }\n }\n\n return null;\n}\n\n/**\n * Compacts an IRI or keyword into a term or prefix if it can be. If the\n * IRI has an associated value it may be passed.\n *\n * @param activeCtx the active context to use.\n * @param iri the IRI to compact.\n * @param value the value to check or null.\n * @param relativeTo options for how to compact IRIs:\n * vocab: true to split after @vocab, false not to.\n * @param reverse true if a reverse property is being compacted, false if not.\n *\n * @return the compacted term, prefix, keyword alias, or the original IRI.\n */\nfunction _compactIri(activeCtx, iri, value, relativeTo, reverse) {\n // can't compact null\n if(iri === null) {\n return iri;\n }\n\n // default value and parent to null\n if(_isUndefined(value)) {\n value = null;\n }\n // default reverse to false\n if(_isUndefined(reverse)) {\n reverse = false;\n }\n relativeTo = relativeTo || {};\n\n var inverseCtx = activeCtx.getInverse();\n\n // if term is a keyword, it can only be compacted to a simple alias\n if(_isKeyword(iri)) {\n if(iri in inverseCtx) {\n return inverseCtx[iri]['@none']['@type']['@none'];\n }\n return iri;\n }\n\n // use inverse context to pick a term if iri is relative to vocab\n if(relativeTo.vocab && iri in inverseCtx) {\n var defaultLanguage = activeCtx['@language'] || '@none';\n\n // prefer @index if available in value\n var containers = [];\n if(_isObject(value) && '@index' in value) {\n containers.push('@index');\n }\n\n // defaults for term selection based on type/language\n var typeOrLanguage = '@language';\n var typeOrLanguageValue = '@null';\n\n if(reverse) {\n typeOrLanguage = '@type';\n typeOrLanguageValue = '@reverse';\n containers.push('@set');\n } else if(_isList(value)) {\n // choose the most specific term that works for all elements in @list\n // only select @list containers if @index is NOT in value\n if(!('@index' in value)) {\n containers.push('@list');\n }\n var list = value['@list'];\n var commonLanguage = (list.length === 0) ? defaultLanguage : null;\n var commonType = null;\n for(var i = 0; i < list.length; ++i) {\n var item = list[i];\n var itemLanguage = '@none';\n var itemType = '@none';\n if(_isValue(item)) {\n if('@language' in item) {\n itemLanguage = item['@language'];\n } else if('@type' in item) {\n itemType = item['@type'];\n } else {\n // plain literal\n itemLanguage = '@null';\n }\n } else {\n itemType = '@id';\n }\n if(commonLanguage === null) {\n commonLanguage = itemLanguage;\n } else if(itemLanguage !== commonLanguage && _isValue(item)) {\n commonLanguage = '@none';\n }\n if(commonType === null) {\n commonType = itemType;\n } else if(itemType !== commonType) {\n commonType = '@none';\n }\n // there are different languages and types in the list, so choose\n // the most generic term, no need to keep iterating the list\n if(commonLanguage === '@none' && commonType === '@none') {\n break;\n }\n }\n commonLanguage = commonLanguage || '@none';\n commonType = commonType || '@none';\n if(commonType !== '@none') {\n typeOrLanguage = '@type';\n typeOrLanguageValue = commonType;\n } else {\n typeOrLanguageValue = commonLanguage;\n }\n } else {\n if(_isValue(value)) {\n if('@language' in value && !('@index' in value)) {\n containers.push('@language');\n typeOrLanguageValue = value['@language'];\n } else if('@type' in value) {\n typeOrLanguage = '@type';\n typeOrLanguageValue = value['@type'];\n }\n } else {\n typeOrLanguage = '@type';\n typeOrLanguageValue = '@id';\n }\n containers.push('@set');\n }\n\n // do term selection\n containers.push('@none');\n var term = _selectTerm(\n activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue);\n if(term !== null) {\n return term;\n }\n }\n\n // no term match, use @vocab if available\n if(relativeTo.vocab) {\n if('@vocab' in activeCtx) {\n // determine if vocab is a prefix of the iri\n var vocab = activeCtx['@vocab'];\n if(iri.indexOf(vocab) === 0 && iri !== vocab) {\n // use suffix as relative iri if it is not a term in the active context\n var suffix = iri.substr(vocab.length);\n if(!(suffix in activeCtx.mappings)) {\n return suffix;\n }\n }\n }\n }\n\n // no term or @vocab match, check for possible CURIEs\n var choice = null;\n var idx = 0;\n var partialMatches = [];\n var iriMap = activeCtx.fastCurieMap;\n // check for partial matches of against `iri`, which means look until\n // iri.length - 1, not full length\n var maxPartialLength = iri.length - 1;\n for(; idx < maxPartialLength && iri[idx] in iriMap; ++idx) {\n iriMap = iriMap[iri[idx]];\n if('' in iriMap) {\n partialMatches.push(iriMap[''][0]);\n }\n }\n // check partial matches in reverse order to prefer longest ones first\n for(var i = partialMatches.length - 1; i >= 0; --i) {\n var entry = partialMatches[i];\n var terms = entry.terms;\n for(var ti = 0; ti < terms.length; ++ti) {\n // a CURIE is usable if:\n // 1. it has no mapping, OR\n // 2. value is null, which means we're not compacting an @value, AND\n // the mapping matches the IRI\n var curie = terms[ti] + ':' + iri.substr(entry.iri.length);\n var isUsableCurie = (!(curie in activeCtx.mappings) ||\n (value === null && activeCtx.mappings[curie]['@id'] === iri));\n\n // select curie if it is shorter or the same length but lexicographically\n // less than the current choice\n if(isUsableCurie && (choice === null ||\n _compareShortestLeast(curie, choice) < 0)) {\n choice = curie;\n }\n }\n }\n\n // return chosen curie\n if(choice !== null) {\n return choice;\n }\n\n // compact IRI relative to base\n if(!relativeTo.vocab) {\n return _removeBase(activeCtx['@base'], iri);\n }\n\n // return IRI as is\n return iri;\n}\n\n/**\n * Performs value compaction on an object with '@value' or '@id' as the only\n * property.\n *\n * @param activeCtx the active context.\n * @param activeProperty the active property that points to the value.\n * @param value the value to compact.\n *\n * @return the compaction result.\n */\nfunction _compactValue(activeCtx, activeProperty, value) {\n // value is a @value\n if(_isValue(value)) {\n // get context rules\n var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');\n var language = jsonld.getContextValue(\n activeCtx, activeProperty, '@language');\n var container = jsonld.getContextValue(\n activeCtx, activeProperty, '@container');\n\n // whether or not the value has an @index that must be preserved\n var preserveIndex = (('@index' in value) &&\n container !== '@index');\n\n // if there's no @index to preserve ...\n if(!preserveIndex) {\n // matching @type or @language specified in context, compact value\n if(value['@type'] === type || value['@language'] === language) {\n return value['@value'];\n }\n }\n\n // return just the value of @value if all are true:\n // 1. @value is the only key or @index isn't being preserved\n // 2. there is no default language or @value is not a string or\n // the key has a mapping with a null @language\n var keyCount = Object.keys(value).length;\n var isValueOnlyKey = (keyCount === 1 ||\n (keyCount === 2 && ('@index' in value) && !preserveIndex));\n var hasDefaultLanguage = ('@language' in activeCtx);\n var isValueString = _isString(value['@value']);\n var hasNullMapping = (activeCtx.mappings[activeProperty] &&\n activeCtx.mappings[activeProperty]['@language'] === null);\n if(isValueOnlyKey &&\n (!hasDefaultLanguage || !isValueString || hasNullMapping)) {\n return value['@value'];\n }\n\n var rval = {};\n\n // preserve @index\n if(preserveIndex) {\n rval[_compactIri(activeCtx, '@index')] = value['@index'];\n }\n\n if('@type' in value) {\n // compact @type IRI\n rval[_compactIri(activeCtx, '@type')] = _compactIri(\n activeCtx, value['@type'], null, {vocab: true});\n } else if('@language' in value) {\n // alias @language\n rval[_compactIri(activeCtx, '@language')] = value['@language'];\n }\n\n // alias @value\n rval[_compactIri(activeCtx, '@value')] = value['@value'];\n\n return rval;\n }\n\n // value is a subject reference\n var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});\n var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');\n var compacted = _compactIri(\n activeCtx, value['@id'], null, {vocab: type === '@vocab'});\n\n // compact to scalar\n if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') {\n return compacted;\n }\n\n var rval = {};\n rval[_compactIri(activeCtx, '@id')] = compacted;\n return rval;\n}\n\n/**\n * Creates a term definition during context processing.\n *\n * @param activeCtx the current active context.\n * @param localCtx the local context being processed.\n * @param term the term in the local context to define the mapping for.\n * @param defined a map of defining/defined keys to detect cycles and prevent\n * double definitions.\n */\nfunction _createTermDefinition(activeCtx, localCtx, term, defined) {\n if(term in defined) {\n // term already defined\n if(defined[term]) {\n return;\n }\n // cycle detected\n throw new JsonLdError(\n 'Cyclical context definition detected.',\n 'jsonld.CyclicalContext',\n {code: 'cyclic IRI mapping', context: localCtx, term: term});\n }\n\n // now defining term\n defined[term] = false;\n\n if(_isKeyword(term)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; keywords cannot be overridden.',\n 'jsonld.SyntaxError',\n {code: 'keyword redefinition', context: localCtx, term: term});\n }\n\n if(term === '') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a term cannot be an empty string.',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n\n // remove old mapping\n if(activeCtx.mappings[term]) {\n delete activeCtx.mappings[term];\n }\n\n // get context term value\n var value = localCtx[term];\n\n // clear context entry\n if(value === null || (_isObject(value) && value['@id'] === null)) {\n activeCtx.mappings[term] = null;\n defined[term] = true;\n return;\n }\n\n // convert short-hand value to object w/@id\n if(_isString(value)) {\n value = {'@id': value};\n }\n\n if(!_isObject(value)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context property values must be ' +\n 'strings or objects.',\n 'jsonld.SyntaxError',\n {code: 'invalid term definition', context: localCtx});\n }\n\n // create new mapping\n var mapping = activeCtx.mappings[term] = {};\n mapping.reverse = false;\n\n if('@reverse' in value) {\n if('@id' in value) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @reverse term definition must not ' +\n 'contain @id.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n var reverse = value['@reverse'];\n if(!_isString(reverse)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @reverse value must be a string.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n\n // expand and add @id mapping\n var id = _expandIri(\n activeCtx, reverse, {vocab: true, base: false}, localCtx, defined);\n if(!_isAbsoluteIri(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @reverse value must be an ' +\n 'absolute IRI or a blank node identifier.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n mapping['@id'] = id;\n mapping.reverse = true;\n } else if('@id' in value) {\n var id = value['@id'];\n if(!_isString(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @id value must be an array ' +\n 'of strings or a string.',\n 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx});\n }\n if(id !== term) {\n // expand and add @id mapping\n id = _expandIri(\n activeCtx, id, {vocab: true, base: false}, localCtx, defined);\n if(!_isAbsoluteIri(id) && !_isKeyword(id)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; a @context @id value must be an ' +\n 'absolute IRI, a blank node identifier, or a keyword.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx});\n }\n mapping['@id'] = id;\n }\n }\n\n // always compute whether term has a colon as an optimization for\n // _compactIri\n var colon = term.indexOf(':');\n mapping._termHasColon = (colon !== -1);\n\n if(!('@id' in mapping)) {\n // see if the term has a prefix\n if(mapping._termHasColon) {\n var prefix = term.substr(0, colon);\n if(prefix in localCtx) {\n // define parent prefix\n _createTermDefinition(activeCtx, localCtx, prefix, defined);\n }\n\n if(activeCtx.mappings[prefix]) {\n // set @id based on prefix parent\n var suffix = term.substr(colon + 1);\n mapping['@id'] = activeCtx.mappings[prefix]['@id'] + suffix;\n } else {\n // term is an absolute IRI\n mapping['@id'] = term;\n }\n } else {\n // non-IRIs *must* define @ids if @vocab is not available\n if(!('@vocab' in activeCtx)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context terms must define an @id.',\n 'jsonld.SyntaxError',\n {code: 'invalid IRI mapping', context: localCtx, term: term});\n }\n // prepend vocab to term\n mapping['@id'] = activeCtx['@vocab'] + term;\n }\n }\n\n // IRI mapping now defined\n defined[term] = true;\n\n if('@type' in value) {\n var type = value['@type'];\n if(!_isString(type)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type values must be a string.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n\n if(type !== '@id' && type !== '@vocab') {\n // expand @type to full IRI\n type = _expandIri(\n activeCtx, type, {vocab: true, base: false}, localCtx, defined);\n if(!_isAbsoluteIri(type)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type value must be an ' +\n 'absolute IRI.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n if(type.indexOf('_:') === 0) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; an @context @type values must be an IRI, ' +\n 'not a blank node identifier.',\n 'jsonld.SyntaxError',\n {code: 'invalid type mapping', context: localCtx});\n }\n }\n\n // add @type to mapping\n mapping['@type'] = type;\n }\n\n if('@container' in value) {\n var container = value['@container'];\n if(container !== '@list' && container !== '@set' &&\n container !== '@index' && container !== '@language') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container value must be ' +\n 'one of the following: @list, @set, @index, or @language.',\n 'jsonld.SyntaxError',\n {code: 'invalid container mapping', context: localCtx});\n }\n if(mapping.reverse && container !== '@index' && container !== '@set' &&\n container !== null) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @container value for a @reverse ' +\n 'type definition must be @index or @set.', 'jsonld.SyntaxError',\n {code: 'invalid reverse property', context: localCtx});\n }\n\n // add @container to mapping\n mapping['@container'] = container;\n }\n\n if('@language' in value && !('@type' in value)) {\n var language = value['@language'];\n if(language !== null && !_isString(language)) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context @language value must be ' +\n 'a string or null.', 'jsonld.SyntaxError',\n {code: 'invalid language mapping', context: localCtx});\n }\n\n // add @language to mapping\n if(language !== null) {\n language = language.toLowerCase();\n }\n mapping['@language'] = language;\n }\n\n // disallow aliasing @context and @preserve\n var id = mapping['@id'];\n if(id === '@context' || id === '@preserve') {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.',\n 'jsonld.SyntaxError', {code: 'invalid keyword alias', context: localCtx});\n }\n}\n\n/**\n * Expands a string to a full IRI. The string may be a term, a prefix, a\n * relative IRI, or an absolute IRI. The associated absolute IRI will be\n * returned.\n *\n * @param activeCtx the current active context.\n * @param value the string to expand.\n * @param relativeTo options for how to resolve relative IRIs:\n * base: true to resolve against the base IRI, false not to.\n * vocab: true to concatenate after @vocab, false not to.\n * @param localCtx the local context being processed (only given if called\n * during context processing).\n * @param defined a map for tracking cycles in context definitions (only given\n * if called during context processing).\n *\n * @return the expanded value.\n */\nfunction _expandIri(activeCtx, value, relativeTo, localCtx, defined) {\n // already expanded\n if(value === null || _isKeyword(value)) {\n return value;\n }\n\n // ensure value is interpreted as a string\n value = String(value);\n\n // define term dependency if not defined\n if(localCtx && value in localCtx && defined[value] !== true) {\n _createTermDefinition(activeCtx, localCtx, value, defined);\n }\n\n relativeTo = relativeTo || {};\n if(relativeTo.vocab) {\n var mapping = activeCtx.mappings[value];\n\n // value is explicitly ignored with a null mapping\n if(mapping === null) {\n return null;\n }\n\n if(mapping) {\n // value is a term\n return mapping['@id'];\n }\n }\n\n // split value into prefix:suffix\n var colon = value.indexOf(':');\n if(colon !== -1) {\n var prefix = value.substr(0, colon);\n var suffix = value.substr(colon + 1);\n\n // do not expand blank nodes (prefix of '_') or already-absolute\n // IRIs (suffix of '//')\n if(prefix === '_' || suffix.indexOf('//') === 0) {\n return value;\n }\n\n // prefix dependency not defined, define it\n if(localCtx && prefix in localCtx) {\n _createTermDefinition(activeCtx, localCtx, prefix, defined);\n }\n\n // use mapping if prefix is defined\n var mapping = activeCtx.mappings[prefix];\n if(mapping) {\n return mapping['@id'] + suffix;\n }\n\n // already absolute IRI\n return value;\n }\n\n // prepend vocab\n if(relativeTo.vocab && '@vocab' in activeCtx) {\n return activeCtx['@vocab'] + value;\n }\n\n // prepend base\n var rval = value;\n if(relativeTo.base) {\n rval = jsonld.prependBase(activeCtx['@base'], rval);\n }\n\n return rval;\n}\n\nfunction _prependBase(base, iri) {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n // already an absolute IRI\n if(iri.indexOf(':') !== -1) {\n return iri;\n }\n\n // parse base if it is a string\n if(_isString(base)) {\n base = jsonld.url.parse(base || '');\n }\n\n // parse given IRI\n var rel = jsonld.url.parse(iri);\n\n // per RFC3986 5.2.2\n var transform = {\n protocol: base.protocol || ''\n };\n\n if(rel.authority !== null) {\n transform.authority = rel.authority;\n transform.path = rel.path;\n transform.query = rel.query;\n } else {\n transform.authority = base.authority;\n\n if(rel.path === '') {\n transform.path = base.path;\n if(rel.query !== null) {\n transform.query = rel.query;\n } else {\n transform.query = base.query;\n }\n } else {\n if(rel.path.indexOf('/') === 0) {\n // IRI represents an absolute path\n transform.path = rel.path;\n } else {\n // merge paths\n var path = base.path;\n\n // append relative path to the end of the last directory from base\n if(rel.path !== '') {\n path = path.substr(0, path.lastIndexOf('/') + 1);\n if(path.length > 0 && path.substr(-1) !== '/') {\n path += '/';\n }\n path += rel.path;\n }\n\n transform.path = path;\n }\n transform.query = rel.query;\n }\n }\n\n // remove slashes and dots in path\n transform.path = _removeDotSegments(transform.path, !!transform.authority);\n\n // construct URL\n var rval = transform.protocol;\n if(transform.authority !== null) {\n rval += '//' + transform.authority;\n }\n rval += transform.path;\n if(transform.query !== null) {\n rval += '?' + transform.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n}\n\n/**\n * Removes a base IRI from the given absolute IRI.\n *\n * @param base the base IRI.\n * @param iri the absolute IRI.\n *\n * @return the relative IRI if relative to base, otherwise the absolute IRI.\n */\nfunction _removeBase(base, iri) {\n // skip IRI processing\n if(base === null) {\n return iri;\n }\n\n if(_isString(base)) {\n base = jsonld.url.parse(base || '');\n }\n\n // establish base root\n var root = '';\n if(base.href !== '') {\n root += (base.protocol || '') + '//' + (base.authority || '');\n } else if(iri.indexOf('//')) {\n // support network-path reference with empty base\n root += '//';\n }\n\n // IRI not relative to base\n if(iri.indexOf(root) !== 0) {\n return iri;\n }\n\n // remove root from IRI and parse remainder\n var rel = jsonld.url.parse(iri.substr(root.length));\n\n // remove path segments that match (do not remove last segment unless there\n // is a hash or query)\n var baseSegments = base.normalizedPath.split('/');\n var iriSegments = rel.normalizedPath.split('/');\n var last = (rel.fragment || rel.query) ? 0 : 1;\n while(baseSegments.length > 0 && iriSegments.length > last) {\n if(baseSegments[0] !== iriSegments[0]) {\n break;\n }\n baseSegments.shift();\n iriSegments.shift();\n }\n\n // use '../' for each non-matching base segment\n var rval = '';\n if(baseSegments.length > 0) {\n // don't count the last segment (if it ends with '/' last path doesn't\n // count and if it doesn't end with '/' it isn't a path)\n baseSegments.pop();\n for(var i = 0; i < baseSegments.length; ++i) {\n rval += '../';\n }\n }\n\n // prepend remaining segments\n rval += iriSegments.join('/');\n\n // add query and hash\n if(rel.query !== null) {\n rval += '?' + rel.query;\n }\n if(rel.fragment !== null) {\n rval += '#' + rel.fragment;\n }\n\n // handle empty base\n if(rval === '') {\n rval = './';\n }\n\n return rval;\n}\n\n/**\n * Gets the initial context.\n *\n * @param options the options to use:\n * [base] the document base IRI.\n *\n * @return the initial context.\n */\nfunction _getInitialContext(options) {\n var base = jsonld.url.parse(options.base || '');\n return {\n '@base': base,\n mappings: {},\n inverse: null,\n getInverse: _createInverseContext,\n clone: _cloneActiveContext\n };\n\n /**\n * Generates an inverse context for use in the compaction algorithm, if\n * not already generated for the given active context.\n *\n * @return the inverse context.\n */\n function _createInverseContext() {\n var activeCtx = this;\n\n // lazily create inverse\n if(activeCtx.inverse) {\n return activeCtx.inverse;\n }\n var inverse = activeCtx.inverse = {};\n\n // variables for building fast CURIE map\n var fastCurieMap = activeCtx.fastCurieMap = {};\n var irisToTerms = {};\n\n // handle default language\n var defaultLanguage = activeCtx['@language'] || '@none';\n\n // create term selections for each mapping in the context, ordered by\n // shortest and then lexicographically least\n var mappings = activeCtx.mappings;\n var terms = Object.keys(mappings).sort(_compareShortestLeast);\n for(var i = 0; i < terms.length; ++i) {\n var term = terms[i];\n var mapping = mappings[term];\n if(mapping === null) {\n continue;\n }\n\n var container = mapping['@container'] || '@none';\n\n // iterate over every IRI in the mapping\n var ids = mapping['@id'];\n if(!_isArray(ids)) {\n ids = [ids];\n }\n for(var ii = 0; ii < ids.length; ++ii) {\n var iri = ids[ii];\n var entry = inverse[iri];\n var isKeyword = _isKeyword(iri);\n\n if(!entry) {\n // initialize entry\n inverse[iri] = entry = {};\n\n if(!isKeyword && !mapping._termHasColon) {\n // init IRI to term map and fast CURIE prefixes\n irisToTerms[iri] = [term];\n var fastCurieEntry = {iri: iri, terms: irisToTerms[iri]};\n if(iri[0] in fastCurieMap) {\n fastCurieMap[iri[0]].push(fastCurieEntry);\n } else {\n fastCurieMap[iri[0]] = [fastCurieEntry];\n }\n }\n } else if(!isKeyword && !mapping._termHasColon) {\n // add IRI to term match\n irisToTerms[iri].push(term);\n }\n\n // add new entry\n if(!entry[container]) {\n entry[container] = {\n '@language': {},\n '@type': {}\n };\n }\n entry = entry[container];\n\n if(mapping.reverse) {\n // term is preferred for values using @reverse\n _addPreferredTerm(mapping, term, entry['@type'], '@reverse');\n } else if('@type' in mapping) {\n // term is preferred for values using specific type\n _addPreferredTerm(mapping, term, entry['@type'], mapping['@type']);\n } else if('@language' in mapping) {\n // term is preferred for values using specific language\n var language = mapping['@language'] || '@null';\n _addPreferredTerm(mapping, term, entry['@language'], language);\n } else {\n // term is preferred for values w/default language or no type and\n // no language\n // add an entry for the default language\n _addPreferredTerm(mapping, term, entry['@language'], defaultLanguage);\n\n // add entries for no type and no language\n _addPreferredTerm(mapping, term, entry['@type'], '@none');\n _addPreferredTerm(mapping, term, entry['@language'], '@none');\n }\n }\n }\n\n // build fast CURIE map\n for(var key in fastCurieMap) {\n _buildIriMap(fastCurieMap, key, 1);\n }\n\n return inverse;\n }\n\n /**\n * Runs a recursive algorithm to build a lookup map for quickly finding\n * potential CURIEs.\n *\n * @param iriMap the map to build.\n * @param key the current key in the map to work on.\n * @param idx the index into the IRI to compare.\n */\n function _buildIriMap(iriMap, key, idx) {\n var entries = iriMap[key];\n var next = iriMap[key] = {};\n\n var iri;\n var letter;\n for(var i = 0; i < entries.length; ++i) {\n iri = entries[i].iri;\n if(idx >= iri.length) {\n letter = '';\n } else {\n letter = iri[idx];\n }\n if(letter in next) {\n next[letter].push(entries[i]);\n } else {\n next[letter] = [entries[i]];\n }\n }\n\n for(var key in next) {\n if(key === '') {\n continue;\n }\n _buildIriMap(next, key, idx + 1);\n }\n }\n\n /**\n * Adds the term for the given entry if not already added.\n *\n * @param mapping the term mapping.\n * @param term the term to add.\n * @param entry the inverse context typeOrLanguage entry to add to.\n * @param typeOrLanguageValue the key in the entry to add to.\n */\n function _addPreferredTerm(mapping, term, entry, typeOrLanguageValue) {\n if(!(typeOrLanguageValue in entry)) {\n entry[typeOrLanguageValue] = term;\n }\n }\n\n /**\n * Clones an active context, creating a child active context.\n *\n * @return a clone (child) of the active context.\n */\n function _cloneActiveContext() {\n var child = {};\n child['@base'] = this['@base'];\n child.mappings = _clone(this.mappings);\n child.clone = this.clone;\n child.inverse = null;\n child.getInverse = this.getInverse;\n if('@language' in this) {\n child['@language'] = this['@language'];\n }\n if('@vocab' in this) {\n child['@vocab'] = this['@vocab'];\n }\n return child;\n }\n}\n\n/**\n * Returns whether or not the given value is a keyword.\n *\n * @param v the value to check.\n *\n * @return true if the value is a keyword, false if not.\n */\nfunction _isKeyword(v) {\n if(!_isString(v)) {\n return false;\n }\n switch(v) {\n case '@base':\n case '@context':\n case '@container':\n case '@default':\n case '@embed':\n case '@explicit':\n case '@graph':\n case '@id':\n case '@index':\n case '@language':\n case '@list':\n case '@omitDefault':\n case '@preserve':\n case '@requireAll':\n case '@reverse':\n case '@set':\n case '@type':\n case '@value':\n case '@vocab':\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if the given value is an Object.\n *\n * @param v the value to check.\n *\n * @return true if the value is an Object, false if not.\n */\nfunction _isObject(v) {\n return (Object.prototype.toString.call(v) === '[object Object]');\n}\n\n/**\n * Returns true if the given value is an empty Object.\n *\n * @param v the value to check.\n *\n * @return true if the value is an empty Object, false if not.\n */\nfunction _isEmptyObject(v) {\n return _isObject(v) && Object.keys(v).length === 0;\n}\n\n/**\n * Returns true if the given value is an Array.\n *\n * @param v the value to check.\n *\n * @return true if the value is an Array, false if not.\n */\nfunction _isArray(v) {\n return Array.isArray(v);\n}\n\n/**\n * Throws an exception if the given value is not a valid @type value.\n *\n * @param v the value to check.\n */\nfunction _validateTypeValue(v) {\n // can be a string or an empty object\n if(_isString(v) || _isEmptyObject(v)) {\n return;\n }\n\n // must be an array\n var isValid = false;\n if(_isArray(v)) {\n // must contain only strings\n isValid = true;\n for(var i = 0; i < v.length; ++i) {\n if(!(_isString(v[i]))) {\n isValid = false;\n break;\n }\n }\n }\n\n if(!isValid) {\n throw new JsonLdError(\n 'Invalid JSON-LD syntax; \"@type\" value must a string, an array of ' +\n 'strings, or an empty object.', 'jsonld.SyntaxError',\n {code: 'invalid type value', value: v});\n }\n}\n\n/**\n * Returns true if the given value is a String.\n *\n * @param v the value to check.\n *\n * @return true if the value is a String, false if not.\n */\nfunction _isString(v) {\n return (typeof v === 'string' ||\n Object.prototype.toString.call(v) === '[object String]');\n}\n\n/**\n * Returns true if the given value is a Number.\n *\n * @param v the value to check.\n *\n * @return true if the value is a Number, false if not.\n */\nfunction _isNumber(v) {\n return (typeof v === 'number' ||\n Object.prototype.toString.call(v) === '[object Number]');\n}\n\n/**\n * Returns true if the given value is a double.\n *\n * @param v the value to check.\n *\n * @return true if the value is a double, false if not.\n */\nfunction _isDouble(v) {\n return _isNumber(v) && String(v).indexOf('.') !== -1;\n}\n\n/**\n * Returns true if the given value is numeric.\n *\n * @param v the value to check.\n *\n * @return true if the value is numeric, false if not.\n */\nfunction _isNumeric(v) {\n return !isNaN(parseFloat(v)) && isFinite(v);\n}\n\n/**\n * Returns true if the given value is a Boolean.\n *\n * @param v the value to check.\n *\n * @return true if the value is a Boolean, false if not.\n */\nfunction _isBoolean(v) {\n return (typeof v === 'boolean' ||\n Object.prototype.toString.call(v) === '[object Boolean]');\n}\n\n/**\n * Returns true if the given value is undefined.\n *\n * @param v the value to check.\n *\n * @return true if the value is undefined, false if not.\n */\nfunction _isUndefined(v) {\n return (typeof v === 'undefined');\n}\n\n/**\n * Returns true if the given value is a subject with properties.\n *\n * @param v the value to check.\n *\n * @return true if the value is a subject with properties, false if not.\n */\nfunction _isSubject(v) {\n // Note: A value is a subject if all of these hold true:\n // 1. It is an Object.\n // 2. It is not a @value, @set, or @list.\n // 3. It has more than 1 key OR any existing key is not @id.\n var rval = false;\n if(_isObject(v) &&\n !(('@value' in v) || ('@set' in v) || ('@list' in v))) {\n var keyCount = Object.keys(v).length;\n rval = (keyCount > 1 || !('@id' in v));\n }\n return rval;\n}\n\n/**\n * Returns true if the given value is a subject reference.\n *\n * @param v the value to check.\n *\n * @return true if the value is a subject reference, false if not.\n */\nfunction _isSubjectReference(v) {\n // Note: A value is a subject reference if all of these hold true:\n // 1. It is an Object.\n // 2. It has a single key: @id.\n return (_isObject(v) && Object.keys(v).length === 1 && ('@id' in v));\n}\n\n/**\n * Returns true if the given value is a @value.\n *\n * @param v the value to check.\n *\n * @return true if the value is a @value, false if not.\n */\nfunction _isValue(v) {\n // Note: A value is a @value if all of these hold true:\n // 1. It is an Object.\n // 2. It has the @value property.\n return _isObject(v) && ('@value' in v);\n}\n\n/**\n * Returns true if the given value is a @list.\n *\n * @param v the value to check.\n *\n * @return true if the value is a @list, false if not.\n */\nfunction _isList(v) {\n // Note: A value is a @list if all of these hold true:\n // 1. It is an Object.\n // 2. It has the @list property.\n return _isObject(v) && ('@list' in v);\n}\n\n/**\n * Returns true if the given value is a blank node.\n *\n * @param v the value to check.\n *\n * @return true if the value is a blank node, false if not.\n */\nfunction _isBlankNode(v) {\n // Note: A value is a blank node if all of these hold true:\n // 1. It is an Object.\n // 2. If it has an @id key its value begins with '_:'.\n // 3. It has no keys OR is not a @value, @set, or @list.\n var rval = false;\n if(_isObject(v)) {\n if('@id' in v) {\n rval = (v['@id'].indexOf('_:') === 0);\n } else {\n rval = (Object.keys(v).length === 0 ||\n !(('@value' in v) || ('@set' in v) || ('@list' in v)));\n }\n }\n return rval;\n}\n\n/**\n * Returns true if the given value is an absolute IRI, false if not.\n *\n * @param v the value to check.\n *\n * @return true if the value is an absolute IRI, false if not.\n */\nfunction _isAbsoluteIri(v) {\n return _isString(v) && v.indexOf(':') !== -1;\n}\n\n/**\n * Clones an object, array, or string/number. If a typed JavaScript object\n * is given, such as a Date, it will be converted to a string.\n *\n * @param value the value to clone.\n *\n * @return the cloned value.\n */\nfunction _clone(value) {\n if(value && typeof value === 'object') {\n var rval;\n if(_isArray(value)) {\n rval = [];\n for(var i = 0; i < value.length; ++i) {\n rval[i] = _clone(value[i]);\n }\n } else if(_isObject(value)) {\n rval = {};\n for(var key in value) {\n rval[key] = _clone(value[key]);\n }\n } else {\n rval = value.toString();\n }\n return rval;\n }\n return value;\n}\n\n/**\n * Finds all @context URLs in the given JSON-LD input.\n *\n * @param input the JSON-LD input.\n * @param urls a map of URLs (url => false/@contexts).\n * @param replace true to replace the URLs in the given input with the\n * @contexts from the urls map, false not to.\n * @param base the base IRI to use to resolve relative IRIs.\n *\n * @return true if new URLs to retrieve were found, false if not.\n */\nfunction _findContextUrls(input, urls, replace, base) {\n var count = Object.keys(urls).length;\n if(_isArray(input)) {\n for(var i = 0; i < input.length; ++i) {\n _findContextUrls(input[i], urls, replace, base);\n }\n return (count < Object.keys(urls).length);\n } else if(_isObject(input)) {\n for(var key in input) {\n if(key !== '@context') {\n _findContextUrls(input[key], urls, replace, base);\n continue;\n }\n\n // get @context\n var ctx = input[key];\n\n // array @context\n if(_isArray(ctx)) {\n var length = ctx.length;\n for(var i = 0; i < length; ++i) {\n var _ctx = ctx[i];\n if(_isString(_ctx)) {\n _ctx = jsonld.prependBase(base, _ctx);\n // replace w/@context if requested\n if(replace) {\n _ctx = urls[_ctx];\n if(_isArray(_ctx)) {\n // add flattened context\n Array.prototype.splice.apply(ctx, [i, 1].concat(_ctx));\n i += _ctx.length - 1;\n length = ctx.length;\n } else {\n ctx[i] = _ctx;\n }\n } else if(!(_ctx in urls)) {\n // @context URL found\n urls[_ctx] = false;\n }\n }\n }\n } else if(_isString(ctx)) {\n // string @context\n ctx = jsonld.prependBase(base, ctx);\n // replace w/@context if requested\n if(replace) {\n input[key] = urls[ctx];\n } else if(!(ctx in urls)) {\n // @context URL found\n urls[ctx] = false;\n }\n }\n }\n return (count < Object.keys(urls).length);\n }\n return false;\n}\n\n/**\n * Retrieves external @context URLs using the given document loader. Every\n * instance of @context in the input that refers to a URL will be replaced\n * with the JSON @context found at that URL.\n *\n * @param input the JSON-LD input with possible contexts.\n * @param options the options to use:\n * documentLoader(url, callback(err, remoteDoc)) the document loader.\n * @param callback(err, input) called once the operation completes.\n */\nfunction _retrieveContextUrls(input, options, callback) {\n // if any error occurs during URL resolution, quit\n var error = null;\n\n // recursive document loader\n var documentLoader = options.documentLoader;\n var retrieve = function(input, cycles, documentLoader, base, callback) {\n if(Object.keys(cycles).length > MAX_CONTEXT_URLS) {\n error = new JsonLdError(\n 'Maximum number of @context URLs exceeded.',\n 'jsonld.ContextUrlError',\n {code: 'loading remote context failed', max: MAX_CONTEXT_URLS});\n return callback(error);\n }\n\n // for tracking the URLs to retrieve\n var urls = {};\n\n // finished will be called once the URL queue is empty\n var finished = function() {\n // replace all URLs in the input\n _findContextUrls(input, urls, true, base);\n callback(null, input);\n };\n\n // find all URLs in the given input\n if(!_findContextUrls(input, urls, false, base)) {\n // no new URLs in input\n return finished();\n }\n\n // queue all unretrieved URLs\n var queue = [];\n for(var url in urls) {\n if(urls[url] === false) {\n queue.push(url);\n }\n }\n\n // retrieve URLs in queue\n var count = queue.length;\n for(var i = 0; i < queue.length; ++i) {\n (function(url) {\n // check for context URL cycle\n if(url in cycles) {\n error = new JsonLdError(\n 'Cyclical @context URLs detected.',\n 'jsonld.ContextUrlError',\n {code: 'recursive context inclusion', url: url});\n return callback(error);\n }\n var _cycles = _clone(cycles);\n _cycles[url] = true;\n var done = function(err, remoteDoc) {\n // short-circuit if there was an error with another URL\n if(error) {\n return;\n }\n\n var ctx = remoteDoc ? remoteDoc.document : null;\n\n // parse string context as JSON\n if(!err && _isString(ctx)) {\n try {\n ctx = JSON.parse(ctx);\n } catch(ex) {\n err = ex;\n }\n }\n\n // ensure ctx is an object\n if(err) {\n err = new JsonLdError(\n 'Dereferencing a URL did not result in a valid JSON-LD object. ' +\n 'Possible causes are an inaccessible URL perhaps due to ' +\n 'a same-origin policy (ensure the server uses CORS if you are ' +\n 'using client-side JavaScript), too many redirects, a ' +\n 'non-JSON response, or more than one HTTP Link Header was ' +\n 'provided for a remote context.',\n 'jsonld.InvalidUrl',\n {code: 'loading remote context failed', url: url, cause: err});\n } else if(!_isObject(ctx)) {\n err = new JsonLdError(\n 'Dereferencing a URL did not result in a JSON object. The ' +\n 'response was valid JSON, but it was not a JSON object.',\n 'jsonld.InvalidUrl',\n {code: 'invalid remote context', url: url, cause: err});\n }\n if(err) {\n error = err;\n return callback(error);\n }\n\n // use empty context if no @context key is present\n if(!('@context' in ctx)) {\n ctx = {'@context': {}};\n } else {\n ctx = {'@context': ctx['@context']};\n }\n\n // append context URL to context if given\n if(remoteDoc.contextUrl) {\n if(!_isArray(ctx['@context'])) {\n ctx['@context'] = [ctx['@context']];\n }\n ctx['@context'].push(remoteDoc.contextUrl);\n }\n\n // recurse\n retrieve(ctx, _cycles, documentLoader, url, function(err, ctx) {\n if(err) {\n return callback(err);\n }\n urls[url] = ctx['@context'];\n count -= 1;\n if(count === 0) {\n finished();\n }\n });\n };\n var promise = documentLoader(url, done);\n if(promise && 'then' in promise) {\n promise.then(done.bind(null, null), done);\n }\n }(queue[i]));\n }\n };\n retrieve(input, {}, documentLoader, options.base, callback);\n}\n\n// define js 1.8.5 Object.keys method if not present\nif(!Object.keys) {\n Object.keys = function(o) {\n if(o !== Object(o)) {\n throw new TypeError('Object.keys called on non-object');\n }\n var rval = [];\n for(var p in o) {\n if(Object.prototype.hasOwnProperty.call(o, p)) {\n rval.push(p);\n }\n }\n return rval;\n };\n}\n\n/**\n * Parses RDF in the form of N-Quads.\n *\n * @param input the N-Quads input to parse.\n *\n * @return an RDF dataset.\n */\nfunction _parseNQuads(input) {\n // define partial regexes\n var iri = '(?:<([^:]+:[^>]*)>)';\n var bnode = '(_:(?:[A-Za-z0-9]+))';\n var plain = '\"([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"';\n var datatype = '(?:\\\\^\\\\^' + iri + ')';\n var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))';\n var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';\n var comment = '(?:#.*)?';\n var ws = '[ \\\\t]+';\n var wso = '[ \\\\t]*';\n var eoln = /(?:\\r\\n)|(?:\\n)|(?:\\r)/g;\n var empty = new RegExp('^' + wso + comment + '$');\n\n // define quad part regexes\n var subject = '(?:' + iri + '|' + bnode + ')' + ws;\n var property = iri + ws;\n var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;\n var graphName = '(?:\\\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\\\.))';\n\n // full quad regex\n var quad = new RegExp(\n '^' + wso + subject + property + object + graphName + wso + comment + '$');\n\n // build RDF dataset\n var dataset = {};\n\n // split N-Quad input into lines\n var lines = input.split(eoln);\n var lineNumber = 0;\n for(var li = 0; li < lines.length; ++li) {\n var line = lines[li];\n lineNumber++;\n\n // skip empty lines\n if(empty.test(line)) {\n continue;\n }\n\n // parse quad\n var match = line.match(quad);\n if(match === null) {\n throw new JsonLdError(\n 'Error while parsing N-Quads; invalid quad.',\n 'jsonld.ParseError', {line: lineNumber});\n }\n\n // create RDF triple\n var triple = {};\n\n // get subject\n if(!_isUndefined(match[1])) {\n triple.subject = {type: 'IRI', value: match[1]};\n } else {\n triple.subject = {type: 'blank node', value: match[2]};\n }\n\n // get predicate\n triple.predicate = {type: 'IRI', value: match[3]};\n\n // get object\n if(!_isUndefined(match[4])) {\n triple.object = {type: 'IRI', value: match[4]};\n } else if(!_isUndefined(match[5])) {\n triple.object = {type: 'blank node', value: match[5]};\n } else {\n triple.object = {type: 'literal'};\n if(!_isUndefined(match[7])) {\n triple.object.datatype = match[7];\n } else if(!_isUndefined(match[8])) {\n triple.object.datatype = RDF_LANGSTRING;\n triple.object.language = match[8];\n } else {\n triple.object.datatype = XSD_STRING;\n }\n var unescaped = match[6]\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\r/g, '\\r')\n .replace(/\\\\\\\\/g, '\\\\');\n triple.object.value = unescaped;\n }\n\n // get graph name ('@default' is used for the default graph)\n var name = '@default';\n if(!_isUndefined(match[9])) {\n name = match[9];\n } else if(!_isUndefined(match[10])) {\n name = match[10];\n }\n\n // initialize graph in dataset\n if(!(name in dataset)) {\n dataset[name] = [triple];\n } else {\n // add triple if unique to its graph\n var unique = true;\n var triples = dataset[name];\n for(var ti = 0; unique && ti < triples.length; ++ti) {\n if(_compareRDFTriples(triples[ti], triple)) {\n unique = false;\n }\n }\n if(unique) {\n triples.push(triple);\n }\n }\n }\n\n return dataset;\n}\n\n// register the N-Quads RDF parser\njsonld.registerRDFParser('application/nquads', _parseNQuads);\n\n/**\n * Converts an RDF dataset to N-Quads.\n *\n * @param dataset the RDF dataset to convert.\n *\n * @return the N-Quads string.\n */\nfunction _toNQuads(dataset) {\n var quads = [];\n for(var graphName in dataset) {\n var triples = dataset[graphName];\n for(var ti = 0; ti < triples.length; ++ti) {\n var triple = triples[ti];\n if(graphName === '@default') {\n graphName = null;\n }\n quads.push(_toNQuad(triple, graphName));\n }\n }\n return quads.sort().join('');\n}\n\n/**\n * Converts an RDF triple and graph name to an N-Quad string (a single quad).\n *\n * @param triple the RDF triple or quad to convert (a triple or quad may be\n * passed, if a triple is passed then `graphName` should be given\n * to specify the name of the graph the triple is in, `null` for\n * the default graph).\n * @param graphName the name of the graph containing the triple, null for\n * the default graph.\n *\n * @return the N-Quad string.\n */\nfunction _toNQuad(triple, graphName) {\n var s = triple.subject;\n var p = triple.predicate;\n var o = triple.object;\n var g = graphName || null;\n if('name' in triple && triple.name) {\n g = triple.name.value;\n }\n\n var quad = '';\n\n // subject is an IRI\n if(s.type === 'IRI') {\n quad += '<' + s.value + '>';\n } else {\n quad += s.value;\n }\n quad += ' ';\n\n // predicate is an IRI\n if(p.type === 'IRI') {\n quad += '<' + p.value + '>';\n } else {\n quad += p.value;\n }\n quad += ' ';\n\n // object is IRI, bnode, or literal\n if(o.type === 'IRI') {\n quad += '<' + o.value + '>';\n } else if(o.type === 'blank node') {\n quad += o.value;\n } else {\n var escaped = o.value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\\"/g, '\\\\\"');\n quad += '\"' + escaped + '\"';\n if(o.datatype === RDF_LANGSTRING) {\n if(o.language) {\n quad += '@' + o.language;\n }\n } else if(o.datatype !== XSD_STRING) {\n quad += '^^<' + o.datatype + '>';\n }\n }\n\n // graph\n if(g !== null && g !== undefined) {\n if(g.indexOf('_:') !== 0) {\n quad += ' <' + g + '>';\n } else {\n quad += ' ' + g;\n }\n }\n\n quad += ' .\\n';\n return quad;\n}\n\n/**\n * Parses the RDF dataset found via the data object from the RDFa API.\n *\n * @param data the RDFa API data object.\n *\n * @return the RDF dataset.\n */\nfunction _parseRdfaApiData(data) {\n var dataset = {};\n dataset['@default'] = [];\n\n var subjects = data.getSubjects();\n for(var si = 0; si < subjects.length; ++si) {\n var subject = subjects[si];\n if(subject === null) {\n continue;\n }\n\n // get all related triples\n var triples = data.getSubjectTriples(subject);\n if(triples === null) {\n continue;\n }\n var predicates = triples.predicates;\n for(var predicate in predicates) {\n // iterate over objects\n var objects = predicates[predicate].objects;\n for(var oi = 0; oi < objects.length; ++oi) {\n var object = objects[oi];\n\n // create RDF triple\n var triple = {};\n\n // add subject\n if(subject.indexOf('_:') === 0) {\n triple.subject = {type: 'blank node', value: subject};\n } else {\n triple.subject = {type: 'IRI', value: subject};\n }\n\n // add predicate\n if(predicate.indexOf('_:') === 0) {\n triple.predicate = {type: 'blank node', value: predicate};\n } else {\n triple.predicate = {type: 'IRI', value: predicate};\n }\n\n // serialize XML literal\n var value = object.value;\n if(object.type === RDF_XML_LITERAL) {\n // initialize XMLSerializer\n if(!XMLSerializer) {\n _defineXMLSerializer();\n }\n var serializer = new XMLSerializer();\n value = '';\n for(var x = 0; x < object.value.length; x++) {\n if(object.value[x].nodeType === Node.ELEMENT_NODE) {\n value += serializer.serializeToString(object.value[x]);\n } else if(object.value[x].nodeType === Node.TEXT_NODE) {\n value += object.value[x].nodeValue;\n }\n }\n }\n\n // add object\n triple.object = {};\n\n // object is an IRI\n if(object.type === RDF_OBJECT) {\n if(object.value.indexOf('_:') === 0) {\n triple.object.type = 'blank node';\n } else {\n triple.object.type = 'IRI';\n }\n } else {\n // object is a literal\n triple.object.type = 'literal';\n if(object.type === RDF_PLAIN_LITERAL) {\n if(object.language) {\n triple.object.datatype = RDF_LANGSTRING;\n triple.object.language = object.language;\n } else {\n triple.object.datatype = XSD_STRING;\n }\n } else {\n triple.object.datatype = object.type;\n }\n }\n triple.object.value = value;\n\n // add triple to dataset in default graph\n dataset['@default'].push(triple);\n }\n }\n }\n\n return dataset;\n}\n\n// register the RDFa API RDF parser\njsonld.registerRDFParser('rdfa-api', _parseRdfaApiData);\n\n/**\n * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique\n * identifiers, keeping track of any previously issued identifiers.\n *\n * @param prefix the prefix to use ('').\n */\nfunction IdentifierIssuer(prefix) {\n this.prefix = prefix;\n this.counter = 0;\n this.existing = {};\n}\njsonld.IdentifierIssuer = IdentifierIssuer;\n// backwards-compability\njsonld.UniqueNamer = IdentifierIssuer;\n\n/**\n * Copies this IdentifierIssuer.\n *\n * @return a copy of this IdentifierIssuer.\n */\nIdentifierIssuer.prototype.clone = function() {\n var copy = new IdentifierIssuer(this.prefix);\n copy.counter = this.counter;\n copy.existing = _clone(this.existing);\n return copy;\n};\n\n/**\n * Gets the new identifier for the given old identifier, where if no old\n * identifier is given a new identifier will be generated.\n *\n * @param [old] the old identifier to get the new identifier for.\n *\n * @return the new identifier.\n */\nIdentifierIssuer.prototype.getId = function(old) {\n // return existing old identifier\n if(old && old in this.existing) {\n return this.existing[old];\n }\n\n // get next identifier\n var identifier = this.prefix + this.counter;\n this.counter += 1;\n\n // save mapping\n if(old) {\n this.existing[old] = identifier;\n }\n\n return identifier;\n};\n// alias\nIdentifierIssuer.prototype.getName = IdentifierIssuer.prototype.getName;\n\n/**\n * Returns true if the given old identifer has already been assigned a new\n * identifier.\n *\n * @param old the old identifier to check.\n *\n * @return true if the old identifier has been assigned a new identifier, false\n * if not.\n */\nIdentifierIssuer.prototype.hasId = function(old) {\n return (old in this.existing);\n};\n// alias\nIdentifierIssuer.prototype.isNamed = IdentifierIssuer.prototype.hasId;\n\n/**\n * A Permutator iterates over all possible permutations of the given array\n * of elements.\n *\n * @param list the array of elements to iterate over.\n */\nvar Permutator = function(list) {\n // original array\n this.list = list.sort();\n // indicates whether there are more permutations\n this.done = false;\n // directional info for permutation algorithm\n this.left = {};\n for(var i = 0; i < list.length; ++i) {\n this.left[list[i]] = true;\n }\n};\n\n/**\n * Returns true if there is another permutation.\n *\n * @return true if there is another permutation, false if not.\n */\nPermutator.prototype.hasNext = function() {\n return !this.done;\n};\n\n/**\n * Gets the next permutation. Call hasNext() to ensure there is another one\n * first.\n *\n * @return the next permutation.\n */\nPermutator.prototype.next = function() {\n // copy current permutation\n var rval = this.list.slice();\n\n /* Calculate the next permutation using the Steinhaus-Johnson-Trotter\n permutation algorithm. */\n\n // get largest mobile element k\n // (mobile: element is greater than the one it is looking at)\n var k = null;\n var pos = 0;\n var length = this.list.length;\n for(var i = 0; i < length; ++i) {\n var element = this.list[i];\n var left = this.left[element];\n if((k === null || element > k) &&\n ((left && i > 0 && element > this.list[i - 1]) ||\n (!left && i < (length - 1) && element > this.list[i + 1]))) {\n k = element;\n pos = i;\n }\n }\n\n // no more permutations\n if(k === null) {\n this.done = true;\n } else {\n // swap k and the element it is looking at\n var swap = this.left[k] ? pos - 1 : pos + 1;\n this.list[pos] = this.list[swap];\n this.list[swap] = k;\n\n // reverse the direction of all elements larger than k\n for(var i = 0; i < length; ++i) {\n if(this.list[i] > k) {\n this.left[this.list[i]] = !this.left[this.list[i]];\n }\n }\n }\n\n return rval;\n};\n\n//////////////////////// DEFINE NORMALIZATION HASH API ////////////////////////\n\n/**\n * Creates a new NormalizeHash for use by the given normalization algorithm.\n *\n * @param algorithm the RDF Dataset Normalization algorithm to use:\n * 'URDNA2015' or 'URGNA2012'.\n */\nvar NormalizeHash = function(algorithm) {\n if(!(this instanceof NormalizeHash)) {\n return new NormalizeHash(algorithm);\n }\n if(['URDNA2015', 'URGNA2012'].indexOf(algorithm) === -1) {\n throw new Error(\n 'Invalid RDF Dataset Normalization algorithm: ' + algorithm);\n }\n NormalizeHash._init.call(this, algorithm);\n};\nNormalizeHash.hashNQuads = function(algorithm, nquads) {\n var md = new NormalizeHash(algorithm);\n for(var i = 0; i < nquads.length; ++i) {\n md.update(nquads[i]);\n }\n return md.digest();\n};\n\n// switch definition of NormalizeHash based on environment\n(function(_nodejs) {\n\nif(_nodejs) {\n // define NormalizeHash using native crypto lib\n var crypto = require('crypto');\n NormalizeHash._init = function(algorithm) {\n if(algorithm === 'URDNA2015') {\n algorithm = 'sha256';\n } else {\n // assume URGNA2012\n algorithm = 'sha1';\n }\n this.md = crypto.createHash(algorithm);\n };\n NormalizeHash.prototype.update = function(msg) {\n return this.md.update(msg, 'utf8');\n };\n NormalizeHash.prototype.digest = function() {\n return this.md.digest('hex');\n };\n return;\n}\n\n// define NormalizeHash using JavaScript\nNormalizeHash._init = function(algorithm) {\n if(algorithm === 'URDNA2015') {\n algorithm = new sha256.Algorithm();\n } else {\n // assume URGNA2012\n algorithm = new sha1.Algorithm();\n }\n this.md = new MessageDigest(algorithm);\n};\nNormalizeHash.prototype.update = function(msg) {\n return this.md.update(msg);\n};\nNormalizeHash.prototype.digest = function() {\n return this.md.digest().toHex();\n};\n\n/////////////////////////// DEFINE MESSAGE DIGEST API /////////////////////////\n\n/**\n * Creates a new MessageDigest.\n *\n * @param algorithm the algorithm to use.\n */\nvar MessageDigest = function(algorithm) {\n if(!(this instanceof MessageDigest)) {\n return new MessageDigest(algorithm);\n }\n\n this._algorithm = algorithm;\n\n // create shared padding as needed\n if(!MessageDigest._padding ||\n MessageDigest._padding.length < this._algorithm.blockSize) {\n MessageDigest._padding = String.fromCharCode(128);\n var c = String.fromCharCode(0x00);\n var n = 64;\n while(n > 0) {\n if(n & 1) {\n MessageDigest._padding += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n }\n\n // start digest automatically for first time\n this.start();\n};\n\n/**\n * Starts the digest.\n *\n * @return this digest object.\n */\nMessageDigest.prototype.start = function() {\n // up to 56-bit message length for convenience\n this.messageLength = 0;\n\n // full message length\n this.fullMessageLength = [];\n var int32s = this._algorithm.messageLengthSize / 4;\n for(var i = 0; i < int32s; ++i) {\n this.fullMessageLength.push(0);\n }\n\n // input buffer\n this._input = new MessageDigest.ByteBuffer();\n\n // get starting state\n this.state = this._algorithm.start();\n\n return this;\n};\n\n/**\n * Updates the digest with the given message input. The input must be\n * a string of characters.\n *\n * @param msg the message input to update with (ByteBuffer or string).\n *\n * @return this digest object.\n */\nMessageDigest.prototype.update = function(msg) {\n // encode message as a UTF-8 encoded binary string\n msg = new MessageDigest.ByteBuffer(unescape(encodeURIComponent(msg)));\n\n // update message length\n this.messageLength += msg.length();\n var len = msg.length();\n len = [(len / 0x100000000) >>> 0, len >>> 0];\n for(var i = this.fullMessageLength.length - 1; i >= 0; --i) {\n this.fullMessageLength[i] += len[1];\n len[1] = len[0] + ((this.fullMessageLength[i] / 0x100000000) >>> 0);\n this.fullMessageLength[i] = this.fullMessageLength[i] >>> 0;\n len[0] = ((len[1] / 0x100000000) >>> 0);\n }\n\n // add bytes to input buffer\n this._input.putBytes(msg.bytes());\n\n // digest blocks\n while(this._input.length() >= this._algorithm.blockSize) {\n this.state = this._algorithm.digest(this.state, this._input);\n }\n\n // compact input buffer every 2K or if empty\n if(this._input.read > 2048 || this._input.length() === 0) {\n this._input.compact();\n }\n\n return this;\n};\n\n/**\n * Produces the digest.\n *\n * @return a byte buffer containing the digest value.\n */\nMessageDigest.prototype.digest = function() {\n /* Note: Here we copy the remaining bytes in the input buffer and add the\n appropriate padding. Then we do the final update on a copy of the state so\n that if the user wants to get intermediate digests they can do so. */\n\n /* Determine the number of bytes that must be added to the message to\n ensure its length is appropriately congruent. In other words, the data to\n be digested must be a multiple of `blockSize`. This data includes the\n message, some padding, and the length of the message. Since the length of\n the message will be encoded as `messageLengthSize` bytes, that means that\n the last segment of the data must have `blockSize` - `messageLengthSize`\n bytes of message and padding. Therefore, the length of the message plus the\n padding must be congruent to X mod `blockSize` because\n `blockSize` - `messageLengthSize` = X.\n\n For example, SHA-1 is congruent to 448 mod 512 and SHA-512 is congruent to\n 896 mod 1024. SHA-1 uses a `blockSize` of 64 bytes (512 bits) and a\n `messageLengthSize` of 8 bytes (64 bits). SHA-512 uses a `blockSize` of\n 128 bytes (1024 bits) and a `messageLengthSize` of 16 bytes (128 bits).\n\n In order to fill up the message length it must be filled with padding that\n begins with 1 bit followed by all 0 bits. Padding must *always* be present,\n so if the message length is already congruent, then `blockSize` padding bits\n must be added. */\n\n // create final block\n var finalBlock = new MessageDigest.ByteBuffer();\n finalBlock.putBytes(this._input.bytes());\n\n // compute remaining size to be digested (include message length size)\n var remaining = (\n this.fullMessageLength[this.fullMessageLength.length - 1] +\n this._algorithm.messageLengthSize);\n\n // add padding for overflow blockSize - overflow\n // _padding starts with 1 byte with first bit is set (byte value 128), then\n // there may be up to (blockSize - 1) other pad bytes\n var overflow = remaining & (this._algorithm.blockSize - 1);\n finalBlock.putBytes(MessageDigest._padding.substr(\n 0, this._algorithm.blockSize - overflow));\n\n // serialize message length in bits in big-endian order; since length\n // is stored in bytes we multiply by 8 (left shift by 3 and merge in\n // remainder from )\n var messageLength = new MessageDigest.ByteBuffer();\n for(var i = 0; i < this.fullMessageLength.length; ++i) {\n messageLength.putInt32((this.fullMessageLength[i] << 3) |\n (this.fullMessageLength[i + 1] >>> 28));\n }\n\n // write the length of the message (algorithm-specific)\n this._algorithm.writeMessageLength(finalBlock, messageLength);\n\n // digest final block\n var state = this._algorithm.digest(this.state.copy(), finalBlock);\n\n // write state to buffer\n var rval = new MessageDigest.ByteBuffer();\n state.write(rval);\n return rval;\n};\n\n/**\n * Creates a simple byte buffer for message digest operations.\n *\n * @param data the data to put in the buffer.\n */\nMessageDigest.ByteBuffer = function(data) {\n if(typeof data === 'string') {\n this.data = data;\n } else {\n this.data = '';\n }\n this.read = 0;\n};\n\n/**\n * Puts a 32-bit integer into this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n */\nMessageDigest.ByteBuffer.prototype.putInt32 = function(i) {\n this.data += (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Gets a 32-bit integer from this buffer in big-endian order and\n * advances the read pointer by 4.\n *\n * @return the word.\n */\nMessageDigest.ByteBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Puts the given bytes into this buffer.\n *\n * @param bytes the bytes as a binary-encoded string.\n */\nMessageDigest.ByteBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n};\n\n/**\n * Gets the bytes in this buffer.\n *\n * @return a string full of UTF-8 encoded characters.\n */\nMessageDigest.ByteBuffer.prototype.bytes = function() {\n return this.data.slice(this.read);\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nMessageDigest.ByteBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Compacts this buffer.\n */\nMessageDigest.ByteBuffer.prototype.compact = function() {\n this.data = this.data.slice(this.read);\n this.read = 0;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nMessageDigest.ByteBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n///////////////////////////// DEFINE SHA-1 ALGORITHM //////////////////////////\n\nvar sha1 = {\n // used for word storage\n _w: null\n};\n\nsha1.Algorithm = function() {\n this.name = 'sha1',\n this.blockSize = 64;\n this.digestLength = 20;\n this.messageLengthSize = 8;\n};\n\nsha1.Algorithm.prototype.start = function() {\n if(!sha1._w) {\n sha1._w = new Array(80);\n }\n return sha1._createState();\n};\n\nsha1.Algorithm.prototype.writeMessageLength = function(\n finalBlock, messageLength) {\n // message length is in bits and in big-endian order; simply append\n finalBlock.putBytes(messageLength.bytes());\n};\n\nsha1.Algorithm.prototype.digest = function(s, input) {\n // consume 512 bit (64 byte) chunks\n var t, a, b, c, d, e, f, i;\n var len = input.length();\n var _w = sha1._w;\n while(len >= 64) {\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n\n // the _w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 80 32-bit words according to SHA-1 algorithm\n // and for 32-79 using Max Locktyukhin's optimization\n\n // round 1\n for(i = 0; i < 16; ++i) {\n t = input.getInt32();\n _w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = t;\n }\n for(; i < 20; ++i) {\n t = (_w[i - 3] ^ _w[i - 8] ^ _w[i - 14] ^ _w[i - 16]);\n t = (t << 1) | (t >>> 31);\n _w[i] = t;\n f = d ^ (b & (c ^ d));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = t;\n }\n // round 2\n for(; i < 32; ++i) {\n t = (_w[i - 3] ^ _w[i - 8] ^ _w[i - 14] ^ _w[i - 16]);\n t = (t << 1) | (t >>> 31);\n _w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = t;\n }\n for(; i < 40; ++i) {\n t = (_w[i - 6] ^ _w[i - 16] ^ _w[i - 28] ^ _w[i - 32]);\n t = (t << 2) | (t >>> 30);\n _w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = t;\n }\n // round 3\n for(; i < 60; ++i) {\n t = (_w[i - 6] ^ _w[i - 16] ^ _w[i - 28] ^ _w[i - 32]);\n t = (t << 2) | (t >>> 30);\n _w[i] = t;\n f = (b & c) | (d & (b ^ c));\n t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = t;\n }\n // round 4\n for(; i < 80; ++i) {\n t = (_w[i - 6] ^ _w[i - 16] ^ _w[i - 28] ^ _w[i - 32]);\n t = (t << 2) | (t >>> 30);\n _w[i] = t;\n f = b ^ c ^ d;\n t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;\n e = d;\n d = c;\n c = (b << 30) | (b >>> 2);\n b = a;\n a = t;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n\n len -= 64;\n }\n\n return s;\n};\n\nsha1._createState = function() {\n var state = {\n h0: 0x67452301,\n h1: 0xEFCDAB89,\n h2: 0x98BADCFE,\n h3: 0x10325476,\n h4: 0xC3D2E1F0\n };\n state.copy = function() {\n var rval = sha1._createState();\n rval.h0 = state.h0;\n rval.h1 = state.h1;\n rval.h2 = state.h2;\n rval.h3 = state.h3;\n rval.h4 = state.h4;\n return rval;\n };\n state.write = function(buffer) {\n buffer.putInt32(state.h0);\n buffer.putInt32(state.h1);\n buffer.putInt32(state.h2);\n buffer.putInt32(state.h3);\n buffer.putInt32(state.h4);\n };\n return state;\n};\n\n//////////////////////////// DEFINE SHA-256 ALGORITHM /////////////////////////\n\nvar sha256 = {\n // shared state\n _k: null,\n _w: null\n};\n\nsha256.Algorithm = function() {\n this.name = 'sha256',\n this.blockSize = 64;\n this.digestLength = 32;\n this.messageLengthSize = 8;\n};\n\nsha256.Algorithm.prototype.start = function() {\n if(!sha256._k) {\n sha256._init();\n }\n return sha256._createState();\n};\n\nsha256.Algorithm.prototype.writeMessageLength = function(\n finalBlock, messageLength) {\n // message length is in bits and in big-endian order; simply append\n finalBlock.putBytes(messageLength.bytes());\n};\n\nsha256.Algorithm.prototype.digest = function(s, input) {\n // consume 512 bit (64 byte) chunks\n var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;\n var len = input.length();\n var _k = sha256._k;\n var _w = sha256._w;\n while(len >= 64) {\n // the w array will be populated with sixteen 32-bit big-endian words\n // and then extended into 64 32-bit words according to SHA-256\n for(i = 0; i < 16; ++i) {\n _w[i] = input.getInt32();\n }\n for(; i < 64; ++i) {\n // XOR word 2 words ago rot right 17, rot right 19, shft right 10\n t1 = _w[i - 2];\n t1 =\n ((t1 >>> 17) | (t1 << 15)) ^\n ((t1 >>> 19) | (t1 << 13)) ^\n (t1 >>> 10);\n // XOR word 15 words ago rot right 7, rot right 18, shft right 3\n t2 = _w[i - 15];\n t2 =\n ((t2 >>> 7) | (t2 << 25)) ^\n ((t2 >>> 18) | (t2 << 14)) ^\n (t2 >>> 3);\n // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32\n _w[i] = (t1 + _w[i - 7] + t2 + _w[i - 16]) | 0;\n }\n\n // initialize hash value for this chunk\n a = s.h0;\n b = s.h1;\n c = s.h2;\n d = s.h3;\n e = s.h4;\n f = s.h5;\n g = s.h6;\n h = s.h7;\n\n // round function\n for(i = 0; i < 64; ++i) {\n // Sum1(e)\n s1 =\n ((e >>> 6) | (e << 26)) ^\n ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n // Ch(e, f, g) (optimized the same way as SHA-1)\n ch = g ^ (e & (f ^ g));\n // Sum0(a)\n s0 =\n ((a >>> 2) | (a << 30)) ^\n ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n // Maj(a, b, c) (optimized the same way as SHA-1)\n maj = (a & b) | (c & (a ^ b));\n\n // main algorithm\n t1 = h + s1 + ch + _k[i] + _w[i];\n t2 = s0 + maj;\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n\n // update hash state\n s.h0 = (s.h0 + a) | 0;\n s.h1 = (s.h1 + b) | 0;\n s.h2 = (s.h2 + c) | 0;\n s.h3 = (s.h3 + d) | 0;\n s.h4 = (s.h4 + e) | 0;\n s.h5 = (s.h5 + f) | 0;\n s.h6 = (s.h6 + g) | 0;\n s.h7 = (s.h7 + h) | 0;\n len -= 64;\n }\n\n return s;\n};\n\nsha256._createState = function() {\n var state = {\n h0: 0x6A09E667,\n h1: 0xBB67AE85,\n h2: 0x3C6EF372,\n h3: 0xA54FF53A,\n h4: 0x510E527F,\n h5: 0x9B05688C,\n h6: 0x1F83D9AB,\n h7: 0x5BE0CD19\n };\n state.copy = function() {\n var rval = sha256._createState();\n rval.h0 = state.h0;\n rval.h1 = state.h1;\n rval.h2 = state.h2;\n rval.h3 = state.h3;\n rval.h4 = state.h4;\n rval.h5 = state.h5;\n rval.h6 = state.h6;\n rval.h7 = state.h7;\n return rval;\n };\n state.write = function(buffer) {\n buffer.putInt32(state.h0);\n buffer.putInt32(state.h1);\n buffer.putInt32(state.h2);\n buffer.putInt32(state.h3);\n buffer.putInt32(state.h4);\n buffer.putInt32(state.h5);\n buffer.putInt32(state.h6);\n buffer.putInt32(state.h7);\n };\n return state;\n};\n\nsha256._init = function() {\n // create K table for SHA-256\n sha256._k = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n\n // used for word storage\n sha256._w = new Array(64);\n};\n\n})(_nodejs); // end definition of NormalizeHash\n\nif(!XMLSerializer) {\n\nvar _defineXMLSerializer = function() {\n XMLSerializer = require('xmldom').XMLSerializer;\n};\n\n} // end _defineXMLSerializer\n\n// define URL parser\n// parseUri 1.2.2\n// (c) Steven Levithan \n// MIT License\n// with local jsonld.js modifications\njsonld.url = {};\njsonld.url.parsers = {\n simple: {\n // RFC 3986 basic parts\n keys: ['href','scheme','authority','path','query','fragment'],\n regex: /^(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?/\n },\n full: {\n keys: ['href','protocol','scheme','authority','auth','user','password','hostname','port','path','directory','file','query','fragment'],\n regex: /^(([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?(?:(((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/\n }\n};\njsonld.url.parse = function(str, parser) {\n var parsed = {};\n var o = jsonld.url.parsers[parser || 'full'];\n var m = o.regex.exec(str);\n var i = o.keys.length;\n while(i--) {\n parsed[o.keys[i]] = (m[i] === undefined) ? null : m[i];\n }\n parsed.normalizedPath = _removeDotSegments(parsed.path, !!parsed.authority);\n return parsed;\n};\n\n/**\n * Removes dot segments from a URL path.\n *\n * @param path the path to remove dot segments from.\n * @param hasAuthority true if the URL has an authority, false if not.\n */\nfunction _removeDotSegments(path, hasAuthority) {\n var rval = '';\n\n if(path.indexOf('/') === 0) {\n rval = '/';\n }\n\n // RFC 3986 5.2.4 (reworked)\n var input = path.split('/');\n var output = [];\n while(input.length > 0) {\n if(input[0] === '.' || (input[0] === '' && input.length > 1)) {\n input.shift();\n continue;\n }\n if(input[0] === '..') {\n input.shift();\n if(hasAuthority ||\n (output.length > 0 && output[output.length - 1] !== '..')) {\n output.pop();\n } else {\n // leading relative URL '..'\n output.push('..');\n }\n continue;\n }\n output.push(input.shift());\n }\n\n return rval + output.join('/');\n}\n\nif(_nodejs) {\n // use node document loader by default\n jsonld.useDocumentLoader('node');\n} else if(typeof XMLHttpRequest !== 'undefined') {\n // use xhr document loader by default\n jsonld.useDocumentLoader('xhr');\n}\n\nif(_nodejs) {\n jsonld.use = function(extension) {\n switch(extension) {\n // TODO: Deprecated as of 0.4.0. Remove at some point.\n case 'request':\n // use node JSON-LD request extension\n jsonld.request = require('jsonld-request');\n break;\n default:\n throw new JsonLdError(\n 'Unknown extension.',\n 'jsonld.UnknownExtension', {extension: extension});\n }\n };\n\n // expose version\n var _module = {exports: {}, filename: __dirname};\n require('pkginfo')(_module, 'version');\n jsonld.version = _module.exports.version;\n}\n\n// end of jsonld API factory\nreturn jsonld;\n};\n\n// external APIs:\n\n// used to generate a new jsonld API instance\nvar factory = function() {\n return wrapper(function() {\n return factory();\n });\n};\n\nif(!_nodejs && (typeof define === 'function' && define.amd)) {\n // export AMD API\n define([], function() {\n // now that module is defined, wrap main jsonld API instance\n wrapper(factory);\n return factory;\n });\n} else {\n // wrap the main jsonld API instance\n wrapper(factory);\n\n if(typeof require === 'function' &&\n typeof module !== 'undefined' && module.exports) {\n // export CommonJS/nodejs API\n module.exports = factory;\n }\n\n if(_browser) {\n // export simple browser API\n if(typeof jsonld === 'undefined') {\n jsonld = jsonldjs = factory;\n } else {\n jsonldjs = factory;\n }\n }\n}\n\nreturn factory;\n\n})();\n","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE\n * @version 2.3.0\n */\n\n(function() {\n \"use strict\";\n function lib$es6$promise$utils$$objectOrFunction(x) {\n return typeof x === 'function' || (typeof x === 'object' && x !== null);\n }\n\n function lib$es6$promise$utils$$isFunction(x) {\n return typeof x === 'function';\n }\n\n function lib$es6$promise$utils$$isMaybeThenable(x) {\n return typeof x === 'object' && x !== null;\n }\n\n var lib$es6$promise$utils$$_isArray;\n if (!Array.isArray) {\n lib$es6$promise$utils$$_isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n } else {\n lib$es6$promise$utils$$_isArray = Array.isArray;\n }\n\n var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;\n var lib$es6$promise$asap$$len = 0;\n var lib$es6$promise$asap$$toString = {}.toString;\n var lib$es6$promise$asap$$vertxNext;\n var lib$es6$promise$asap$$customSchedulerFn;\n\n var lib$es6$promise$asap$$asap = function asap(callback, arg) {\n lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;\n lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;\n lib$es6$promise$asap$$len += 2;\n if (lib$es6$promise$asap$$len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (lib$es6$promise$asap$$customSchedulerFn) {\n lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);\n } else {\n lib$es6$promise$asap$$scheduleFlush();\n }\n }\n }\n\n function lib$es6$promise$asap$$setScheduler(scheduleFn) {\n lib$es6$promise$asap$$customSchedulerFn = scheduleFn;\n }\n\n function lib$es6$promise$asap$$setAsap(asapFn) {\n lib$es6$promise$asap$$asap = asapFn;\n }\n\n var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;\n var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};\n var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;\n var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';\n\n // test for web worker but not in IE10\n var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&\n typeof importScripts !== 'undefined' &&\n typeof MessageChannel !== 'undefined';\n\n // node\n function lib$es6$promise$asap$$useNextTick() {\n var nextTick = process.nextTick;\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // setImmediate should be used instead instead\n var version = process.versions.node.match(/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/);\n if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {\n nextTick = setImmediate;\n }\n return function() {\n nextTick(lib$es6$promise$asap$$flush);\n };\n }\n\n // vertx\n function lib$es6$promise$asap$$useVertxTimer() {\n return function() {\n lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);\n };\n }\n\n function lib$es6$promise$asap$$useMutationObserver() {\n var iterations = 0;\n var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function() {\n node.data = (iterations = ++iterations % 2);\n };\n }\n\n // web worker\n function lib$es6$promise$asap$$useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = lib$es6$promise$asap$$flush;\n return function () {\n channel.port2.postMessage(0);\n };\n }\n\n function lib$es6$promise$asap$$useSetTimeout() {\n return function() {\n setTimeout(lib$es6$promise$asap$$flush, 1);\n };\n }\n\n var lib$es6$promise$asap$$queue = new Array(1000);\n function lib$es6$promise$asap$$flush() {\n for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {\n var callback = lib$es6$promise$asap$$queue[i];\n var arg = lib$es6$promise$asap$$queue[i+1];\n\n callback(arg);\n\n lib$es6$promise$asap$$queue[i] = undefined;\n lib$es6$promise$asap$$queue[i+1] = undefined;\n }\n\n lib$es6$promise$asap$$len = 0;\n }\n\n function lib$es6$promise$asap$$attemptVertex() {\n try {\n var r = require;\n var vertx = r('vertx');\n lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return lib$es6$promise$asap$$useVertxTimer();\n } catch(e) {\n return lib$es6$promise$asap$$useSetTimeout();\n }\n }\n\n var lib$es6$promise$asap$$scheduleFlush;\n // Decide what async method to use to triggering processing of queued callbacks:\n if (lib$es6$promise$asap$$isNode) {\n lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();\n } else if (lib$es6$promise$asap$$BrowserMutationObserver) {\n lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();\n } else if (lib$es6$promise$asap$$isWorker) {\n lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();\n } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {\n lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex();\n } else {\n lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();\n }\n\n function lib$es6$promise$$internal$$noop() {}\n\n var lib$es6$promise$$internal$$PENDING = void 0;\n var lib$es6$promise$$internal$$FULFILLED = 1;\n var lib$es6$promise$$internal$$REJECTED = 2;\n\n var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();\n\n function lib$es6$promise$$internal$$selfFullfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n }\n\n function lib$es6$promise$$internal$$cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n }\n\n function lib$es6$promise$$internal$$getThen(promise) {\n try {\n return promise.then;\n } catch(error) {\n lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;\n return lib$es6$promise$$internal$$GET_THEN_ERROR;\n }\n }\n\n function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch(e) {\n return e;\n }\n }\n\n function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {\n lib$es6$promise$asap$$asap(function(promise) {\n var sealed = false;\n var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {\n if (sealed) { return; }\n sealed = true;\n if (thenable !== value) {\n lib$es6$promise$$internal$$resolve(promise, value);\n } else {\n lib$es6$promise$$internal$$fulfill(promise, value);\n }\n }, function(reason) {\n if (sealed) { return; }\n sealed = true;\n\n lib$es6$promise$$internal$$reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n lib$es6$promise$$internal$$reject(promise, error);\n }\n }, promise);\n }\n\n function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {\n if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {\n lib$es6$promise$$internal$$fulfill(promise, thenable._result);\n } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {\n lib$es6$promise$$internal$$reject(promise, thenable._result);\n } else {\n lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {\n lib$es6$promise$$internal$$resolve(promise, value);\n }, function(reason) {\n lib$es6$promise$$internal$$reject(promise, reason);\n });\n }\n }\n\n function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {\n if (maybeThenable.constructor === promise.constructor) {\n lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);\n } else {\n var then = lib$es6$promise$$internal$$getThen(maybeThenable);\n\n if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {\n lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);\n } else if (then === undefined) {\n lib$es6$promise$$internal$$fulfill(promise, maybeThenable);\n } else if (lib$es6$promise$utils$$isFunction(then)) {\n lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);\n } else {\n lib$es6$promise$$internal$$fulfill(promise, maybeThenable);\n }\n }\n }\n\n function lib$es6$promise$$internal$$resolve(promise, value) {\n if (promise === value) {\n lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment());\n } else if (lib$es6$promise$utils$$objectOrFunction(value)) {\n lib$es6$promise$$internal$$handleMaybeThenable(promise, value);\n } else {\n lib$es6$promise$$internal$$fulfill(promise, value);\n }\n }\n\n function lib$es6$promise$$internal$$publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n lib$es6$promise$$internal$$publish(promise);\n }\n\n function lib$es6$promise$$internal$$fulfill(promise, value) {\n if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }\n\n promise._result = value;\n promise._state = lib$es6$promise$$internal$$FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);\n }\n }\n\n function lib$es6$promise$$internal$$reject(promise, reason) {\n if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }\n promise._state = lib$es6$promise$$internal$$REJECTED;\n promise._result = reason;\n\n lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);\n }\n\n function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {\n var subscribers = parent._subscribers;\n var length = subscribers.length;\n\n parent._onerror = null;\n\n subscribers[length] = child;\n subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;\n subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);\n }\n }\n\n function lib$es6$promise$$internal$$publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) { return; }\n\n var child, callback, detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n }\n\n function lib$es6$promise$$internal$$ErrorObject() {\n this.error = null;\n }\n\n var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();\n\n function lib$es6$promise$$internal$$tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch(e) {\n lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;\n return lib$es6$promise$$internal$$TRY_CATCH_ERROR;\n }\n }\n\n function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {\n var hasCallback = lib$es6$promise$utils$$isFunction(callback),\n value, error, succeeded, failed;\n\n if (hasCallback) {\n value = lib$es6$promise$$internal$$tryCatch(callback, detail);\n\n if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());\n return;\n }\n\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== lib$es6$promise$$internal$$PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n lib$es6$promise$$internal$$resolve(promise, value);\n } else if (failed) {\n lib$es6$promise$$internal$$reject(promise, error);\n } else if (settled === lib$es6$promise$$internal$$FULFILLED) {\n lib$es6$promise$$internal$$fulfill(promise, value);\n } else if (settled === lib$es6$promise$$internal$$REJECTED) {\n lib$es6$promise$$internal$$reject(promise, value);\n }\n }\n\n function lib$es6$promise$$internal$$initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value){\n lib$es6$promise$$internal$$resolve(promise, value);\n }, function rejectPromise(reason) {\n lib$es6$promise$$internal$$reject(promise, reason);\n });\n } catch(e) {\n lib$es6$promise$$internal$$reject(promise, e);\n }\n }\n\n function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {\n var enumerator = this;\n\n enumerator._instanceConstructor = Constructor;\n enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);\n\n if (enumerator._validateInput(input)) {\n enumerator._input = input;\n enumerator.length = input.length;\n enumerator._remaining = input.length;\n\n enumerator._init();\n\n if (enumerator.length === 0) {\n lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);\n } else {\n enumerator.length = enumerator.length || 0;\n enumerator._enumerate();\n if (enumerator._remaining === 0) {\n lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);\n }\n }\n } else {\n lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());\n }\n }\n\n lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {\n return lib$es6$promise$utils$$isArray(input);\n };\n\n lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {\n return new Error('Array Methods must be provided an Array');\n };\n\n lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {\n this._result = new Array(this.length);\n };\n\n var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;\n\n lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {\n var enumerator = this;\n\n var length = enumerator.length;\n var promise = enumerator.promise;\n var input = enumerator._input;\n\n for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {\n enumerator._eachEntry(input[i], i);\n }\n };\n\n lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {\n var enumerator = this;\n var c = enumerator._instanceConstructor;\n\n if (lib$es6$promise$utils$$isMaybeThenable(entry)) {\n if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {\n entry._onerror = null;\n enumerator._settledAt(entry._state, i, entry._result);\n } else {\n enumerator._willSettleAt(c.resolve(entry), i);\n }\n } else {\n enumerator._remaining--;\n enumerator._result[i] = entry;\n }\n };\n\n lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {\n var enumerator = this;\n var promise = enumerator.promise;\n\n if (promise._state === lib$es6$promise$$internal$$PENDING) {\n enumerator._remaining--;\n\n if (state === lib$es6$promise$$internal$$REJECTED) {\n lib$es6$promise$$internal$$reject(promise, value);\n } else {\n enumerator._result[i] = value;\n }\n }\n\n if (enumerator._remaining === 0) {\n lib$es6$promise$$internal$$fulfill(promise, enumerator._result);\n }\n };\n\n lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {\n var enumerator = this;\n\n lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {\n enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);\n }, function(reason) {\n enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);\n });\n };\n function lib$es6$promise$promise$all$$all(entries) {\n return new lib$es6$promise$enumerator$$default(this, entries).promise;\n }\n var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;\n function lib$es6$promise$promise$race$$race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n var promise = new Constructor(lib$es6$promise$$internal$$noop);\n\n if (!lib$es6$promise$utils$$isArray(entries)) {\n lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));\n return promise;\n }\n\n var length = entries.length;\n\n function onFulfillment(value) {\n lib$es6$promise$$internal$$resolve(promise, value);\n }\n\n function onRejection(reason) {\n lib$es6$promise$$internal$$reject(promise, reason);\n }\n\n for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {\n lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);\n }\n\n return promise;\n }\n var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;\n function lib$es6$promise$promise$resolve$$resolve(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(lib$es6$promise$$internal$$noop);\n lib$es6$promise$$internal$$resolve(promise, object);\n return promise;\n }\n var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;\n function lib$es6$promise$promise$reject$$reject(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(lib$es6$promise$$internal$$noop);\n lib$es6$promise$$internal$$reject(promise, reason);\n return promise;\n }\n var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;\n\n var lib$es6$promise$promise$$counter = 0;\n\n function lib$es6$promise$promise$$needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n }\n\n function lib$es6$promise$promise$$needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n }\n\n var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;\n /**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n var promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n var xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n */\n function lib$es6$promise$promise$$Promise(resolver) {\n this._id = lib$es6$promise$promise$$counter++;\n this._state = undefined;\n this._result = undefined;\n this._subscribers = [];\n\n if (lib$es6$promise$$internal$$noop !== resolver) {\n if (!lib$es6$promise$utils$$isFunction(resolver)) {\n lib$es6$promise$promise$$needsResolver();\n }\n\n if (!(this instanceof lib$es6$promise$promise$$Promise)) {\n lib$es6$promise$promise$$needsNew();\n }\n\n lib$es6$promise$$internal$$initializePromise(this, resolver);\n }\n }\n\n lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;\n lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;\n lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;\n lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;\n lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;\n lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;\n lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;\n\n lib$es6$promise$promise$$Promise.prototype = {\n constructor: lib$es6$promise$promise$$Promise,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n\n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n\n Chaining\n --------\n\n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n\n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n\n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n\n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n\n Assimilation\n ------------\n\n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n\n If the assimliated promise rejects, then the downstream promise will also reject.\n\n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n\n Simple Example\n --------------\n\n Synchronous Example\n\n ```javascript\n var result;\n\n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n\n Errback Example\n\n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n\n Promise Example;\n\n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n\n Advanced Example\n --------------\n\n Synchronous Example\n\n ```javascript\n var author, books;\n\n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n\n Errback Example\n\n ```js\n\n function foundBooks(books) {\n\n }\n\n function failure(reason) {\n\n }\n\n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n\n Promise Example;\n\n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n\n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: function(onFulfillment, onRejection) {\n var parent = this;\n var state = parent._state;\n\n if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {\n return this;\n }\n\n var child = new this.constructor(lib$es6$promise$$internal$$noop);\n var result = parent._result;\n\n if (state) {\n var callback = arguments[state - 1];\n lib$es6$promise$asap$$asap(function(){\n lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);\n });\n } else {\n lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n },\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n\n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n\n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n\n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n\n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function(onRejection) {\n return this.then(null, onRejection);\n }\n };\n function lib$es6$promise$polyfill$$polyfill() {\n var local;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {\n return;\n }\n\n local.Promise = lib$es6$promise$promise$$default;\n }\n var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;\n\n var lib$es6$promise$umd$$ES6Promise = {\n 'Promise': lib$es6$promise$promise$$default,\n 'polyfill': lib$es6$promise$polyfill$$default\n };\n\n /* global define:true module:true window: true */\n if (typeof define === 'function' && define['amd']) {\n define(function() { return lib$es6$promise$umd$$ES6Promise; });\n } else if (typeof module !== 'undefined' && module['exports']) {\n module['exports'] = lib$es6$promise$umd$$ES6Promise;\n } else if (typeof this !== 'undefined') {\n this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;\n }\n\n lib$es6$promise$polyfill$$default();\n}).call(this);\n\n","module.exports = __WEBPACK_EXTERNAL_MODULE__41__;","// Replace local require by a lazy loader\nvar globalRequire = require;\nrequire = function () {};\n\n// Expose submodules\nvar exports = module.exports = {\n Lexer: require('./lib/N3Lexer'),\n Parser: require('./lib/N3Parser'),\n Writer: require('./lib/N3Writer'),\n Store: require('./lib/N3Store'),\n StreamParser: require('./lib/N3StreamParser'),\n StreamWriter: require('./lib/N3StreamWriter'),\n Util: require('./lib/N3Util'),\n};\n\n// Load submodules on first access\nObject.keys(exports).forEach(function (submodule) {\n Object.defineProperty(exports, submodule, {\n configurable: true,\n enumerable: true,\n get: function () {\n delete exports[submodule];\n return exports[submodule] = globalRequire('./lib/N3' + submodule);\n },\n });\n});\n","// **N3Store** objects store N3 triples by graph in memory.\n\nvar expandPrefixedName = require('./N3Util').expandPrefixedName;\n\n// ## Constructor\nfunction N3Store(triples, options) {\n if (!(this instanceof N3Store))\n return new N3Store(triples, options);\n\n // The number of triples is initially zero.\n this._size = 0;\n // `_graphs` contains subject, predicate, and object indexes per graph.\n this._graphs = Object.create(null);\n // `_entities` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers.\n // This saves memory, since only the numbers have to be stored in `_graphs`.\n this._entities = Object.create(null);\n this._entities['><'] = 0; // Dummy entry, so the first actual key is non-zero\n this._entityCount = 0;\n // `_blankNodeIndex` is the index of the last created blank node that was automatically named\n this._blankNodeIndex = 0;\n\n // Shift parameters if `triples` is not given\n if (!options && triples && !triples[0])\n options = triples, triples = null;\n\n // Add triples and prefixes if passed\n this._prefixes = Object.create(null);\n if (options && options.prefixes)\n this.addPrefixes(options.prefixes);\n if (triples)\n this.addTriples(triples);\n}\n\nN3Store.prototype = {\n // ## Public properties\n\n // ### `size` returns the number of triples in the store.\n get size() {\n // Return the triple count if if was cached.\n var size = this._size;\n if (size !== null)\n return size;\n\n // Calculate the number of triples by counting to the deepest level.\n var graphs = this._graphs, subjects, subject;\n for (var graphKey in graphs)\n for (var subjectKey in (subjects = graphs[graphKey].subjects))\n for (var predicateKey in (subject = subjects[subjectKey]))\n size += Object.keys(subject[predicateKey]).length;\n return this._size = size;\n },\n\n // ## Private methods\n\n // ### `_addToIndex` adds a triple to a three-layered index.\n _addToIndex: function (index0, key0, key1, key2) {\n // Create layers as necessary.\n var index1 = index0[key0] || (index0[key0] = {});\n var index2 = index1[key1] || (index1[key1] = {});\n // Setting the key to _any_ value signalizes the presence of the triple.\n index2[key2] = null;\n },\n\n // ### `_removeFromIndex` removes a triple from a three-layered index.\n _removeFromIndex: function (index0, key0, key1, key2) {\n // Remove the triple from the index.\n var index1 = index0[key0], index2 = index1[key1], key;\n delete index2[key2];\n\n // Remove intermediary index layers if they are empty.\n for (key in index2) return;\n delete index1[key1];\n for (key in index1) return;\n delete index0[key0];\n },\n\n // ### `_findInIndex` finds a set of triples in a three-layered index.\n // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.\n // Any of these keys can be `null`, which is interpreted as a wildcard.\n // `name0`, `name1`, and `name2` are the names of the keys at each level,\n // used when reconstructing the resulting triple\n // (for instance: _subject_, _predicate_, and _object_).\n // Finally, `graph` will be the graph of the created triples.\n _findInIndex: function (index0, key0, key1, key2, name0, name1, name2, graph) {\n var results = [], entityKeys = Object.keys(this._entities), tmp, index1, index2;\n\n // If a key is specified, use only that part of index 0.\n if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];\n for (var value0 in index0) {\n var entity0 = entityKeys[value0];\n\n if (index1 = index0[value0]) {\n // If a key is specified, use only that part of index 1.\n if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];\n for (var value1 in index1) {\n var entity1 = entityKeys[value1];\n\n if (index2 = index1[value1]) {\n // If a key is specified, use only that part of index 2, if it exists.\n var values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2);\n // Create triples for all items found in index 2.\n for (var l = values.length - 1; l >= 0; l--) {\n var result = { subject: '', predicate: '', object: '', graph: graph };\n result[name0] = entity0;\n result[name1] = entity1;\n result[name2] = entityKeys[values[l]];\n results.push(result);\n }\n }\n }\n }\n }\n return results;\n },\n\n // ### `_countInIndex` counts matching triples in a three-layered index.\n // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.\n // Any of these keys can be `null`, which is interpreted as a wildcard.\n _countInIndex: function (index0, key0, key1, key2) {\n var count = 0, tmp, index1, index2;\n\n // If a key is specified, count only that part of index 0.\n if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];\n for (var value0 in index0) {\n if (index1 = index0[value0]) {\n // If a key is specified, count only that part of index 1.\n if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];\n for (var value1 in index1) {\n if (index2 = index1[value1]) {\n // If a key is specified, count the triple if it exists.\n if (key2) (key2 in index2) && count++;\n // Otherwise, count all triples.\n else count += Object.keys(index2).length;\n }\n }\n }\n }\n return count;\n },\n\n // ## Public methods\n\n // ### `addTriple` adds a new N3 triple to the store.\n addTriple: function (subject, predicate, object, graph) {\n // Shift arguments if a triple object is given instead of components\n if (!predicate)\n graph = subject.graph, object = subject.object,\n predicate = subject.predicate, subject = subject.subject;\n\n // Find the graph that will contain the triple.\n graph = graph || '';\n var graphItem = this._graphs[graph];\n // Create the graph if it doesn't exist yet.\n if (!graphItem) {\n graphItem = this._graphs[graph] = { subjects: {}, predicates: {}, objects: {} };\n // Freezing a graph helps subsequent `add` performance,\n // and properties will never be modified anyway.\n Object.freeze(graphItem);\n }\n\n // Since entities can often be long IRIs, we avoid storing them in every index.\n // Instead, we have a separate index that maps entities to numbers,\n // which are then used as keys in the other indexes.\n var entities = this._entities;\n subject = entities[subject] || (entities[subject] = ++this._entityCount);\n predicate = entities[predicate] || (entities[predicate] = ++this._entityCount);\n object = entities[object] || (entities[object] = ++this._entityCount);\n\n this._addToIndex(graphItem.subjects, subject, predicate, object);\n this._addToIndex(graphItem.predicates, predicate, object, subject);\n this._addToIndex(graphItem.objects, object, subject, predicate);\n\n // The cached triple count is now invalid.\n this._size = null;\n },\n\n // ### `addTriples` adds multiple N3 triples to the store.\n addTriples: function (triples) {\n for (var i = triples.length - 1; i >= 0; i--)\n this.addTriple(triples[i]);\n },\n\n // ### `addPrefix` adds support for querying with the given prefix\n addPrefix: function (prefix, iri) {\n this._prefixes[prefix] = iri;\n },\n\n // ### `addPrefixes` adds support for querying with the given prefixes\n addPrefixes: function (prefixes) {\n for (var prefix in prefixes)\n this.addPrefix(prefix, prefixes[prefix]);\n },\n\n // ### `removeTriple` removes an N3 triple from the store if it exists.\n removeTriple: function (subject, predicate, object, graph) {\n // Shift arguments if a triple object is given instead of components.\n if (!predicate)\n graph = subject.graph, object = subject.object,\n predicate = subject.predicate, subject = subject.subject;\n graph = graph || '';\n\n // Find internal identifiers for all components.\n var graphItem, entities = this._entities, graphs = this._graphs;\n if (!(subject = entities[subject])) return;\n if (!(predicate = entities[predicate])) return;\n if (!(object = entities[object])) return;\n if (!(graphItem = graphs[graph])) return;\n\n // Verify that the triple exists.\n var subjects, predicates;\n if (!(subjects = graphItem.subjects[subject])) return;\n if (!(predicates = subjects[predicate])) return;\n if (!(object in predicates)) return;\n\n // Remove it from all indexes.\n this._removeFromIndex(graphItem.subjects, subject, predicate, object);\n this._removeFromIndex(graphItem.predicates, predicate, object, subject);\n this._removeFromIndex(graphItem.objects, object, subject, predicate);\n if (this._size !== null) this._size--;\n\n // Remove the graph if it is empty.\n for (subject in graphItem.subjects) return;\n delete graphs[graph];\n },\n\n // ### `removeTriples` removes multiple N3 triples from the store.\n removeTriples: function (triples) {\n for (var i = triples.length - 1; i >= 0; i--)\n this.removeTriple(triples[i]);\n },\n\n // ### `find` finds a set of triples matching a pattern, expanding prefixes as necessary.\n // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.\n // Setting `graph` to `null` means the default graph.\n find: function (subject, predicate, object, graph) {\n var prefixes = this._prefixes;\n return this.findByIRI(\n expandPrefixedName(subject, prefixes),\n expandPrefixedName(predicate, prefixes),\n expandPrefixedName(object, prefixes),\n expandPrefixedName(graph, prefixes)\n );\n },\n\n // ### `findByIRI` finds a set of triples matching a pattern.\n // Setting `subject`, `predicate`, or `object` to a falsy value means an _anything_ wildcard.\n // Setting `graph` to a falsy value means the default graph.\n findByIRI: function (subject, predicate, object, graph) {\n graph = graph || '';\n var graphItem = this._graphs[graph], entities = this._entities;\n\n // If the specified graph contain no triples, there are no results.\n if (!graphItem) return [];\n\n // Translate IRIs to internal index keys.\n // Optimization: if the entity doesn't exist, no triples with it exist.\n if (subject && !(subject = entities[subject])) return [];\n if (predicate && !(predicate = entities[predicate])) return [];\n if (object && !(object = entities[object])) return [];\n\n // Choose the optimal index, based on what fields are present\n if (subject) {\n if (object)\n // If subject and object are given, the object index will be the fastest.\n return this._findInIndex(graphItem.objects, object, subject, predicate,\n 'object', 'subject', 'predicate', graph);\n else\n // If only subject and possibly predicate are given, the subject index will be the fastest.\n return this._findInIndex(graphItem.subjects, subject, predicate, null,\n 'subject', 'predicate', 'object', graph);\n }\n else if (predicate)\n // If only predicate and possibly object are given, the predicate index will be the fastest.\n return this._findInIndex(graphItem.predicates, predicate, object, null,\n 'predicate', 'object', 'subject', graph);\n else if (object)\n // If only object is given, the object index will be the fastest.\n return this._findInIndex(graphItem.objects, object, null, null,\n 'object', 'subject', 'predicate', graph);\n else\n // If nothing is given, iterate subjects and predicates first\n return this._findInIndex(graphItem.subjects, null, null, null,\n 'subject', 'predicate', 'object', graph);\n },\n\n // ### `count` returns the number of triples matching a pattern, expanding prefixes as necessary.\n // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.\n // Setting `graph` to `null` means the default graph.\n count: function (subject, predicate, object, graph) {\n var prefixes = this._prefixes;\n return this.countByIRI(\n expandPrefixedName(subject, prefixes),\n expandPrefixedName(predicate, prefixes),\n expandPrefixedName(object, prefixes),\n expandPrefixedName(graph, prefixes)\n );\n },\n\n // ### `countByIRI` returns the number of triples matching a pattern.\n // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.\n // Setting `graph` to `null` means the default graph.\n countByIRI: function (subject, predicate, object, graph) {\n graph = graph || '';\n var graphItem = this._graphs[graph], entities = this._entities;\n\n // If the specified graph contain no triples, there are no results.\n if (!graphItem) return 0;\n\n // Translate IRIs to internal index keys.\n // Optimization: if the entity doesn't exist, no triples with it exist.\n if (subject && !(subject = entities[subject])) return 0;\n if (predicate && !(predicate = entities[predicate])) return 0;\n if (object && !(object = entities[object])) return 0;\n\n // Choose the optimal index, based on what fields are present\n if (subject) {\n if (object)\n // If subject and object are given, the object index will be the fastest.\n return this._countInIndex(graphItem.objects, object, subject, predicate);\n else\n // If only subject and possibly predicate are given, the subject index will be the fastest.\n return this._countInIndex(graphItem.subjects, subject, predicate, object);\n }\n else if (predicate) {\n // If only predicate and possibly object are given, the predicate index will be the fastest.\n return this._countInIndex(graphItem.predicates, predicate, object, subject);\n }\n else {\n // If only object is possibly given, the object index will be the fastest.\n return this._countInIndex(graphItem.objects, object, subject, predicate);\n }\n },\n\n // ### `createBlankNode` creates a new blank node, returning its name.\n createBlankNode: function (suggestedName) {\n var name, index;\n // Generate a name based on the suggested name\n if (suggestedName) {\n name = suggestedName = '_:' + suggestedName, index = 1;\n while (this._entities[name])\n name = suggestedName + index++;\n }\n // Generate a generic blank node name\n else {\n do { name = '_:b' + this._blankNodeIndex++; }\n while (this._entities[name]);\n }\n // Add the blank node to the entities, avoiding the generation of duplicates\n this._entities[name] = ++this._entityCount;\n return name;\n },\n};\n\n// ## Exports\n\n// Export the `N3Store` class as a whole.\nmodule.exports = N3Store;\n","// **N3StreamParser** parses an N3 stream into a triple stream\nvar Transform = require('stream').Transform,\n util = require('util'),\n N3Parser = require('./N3Parser.js');\n\n// ## Constructor\nfunction N3StreamParser(options) {\n if (!(this instanceof N3StreamParser))\n return new N3StreamParser(options);\n\n // Initialize Transform base class\n Transform.call(this, { decodeStrings: true });\n this._readableState.objectMode = true;\n\n // Set up parser\n var self = this, parser = new N3Parser(options);\n parser.parse(\n // Handle triples by pushing them down the pipeline\n function (error, triple) {\n triple && self.push(triple) ||\n error && self.emit('error', error);\n },\n // Emit prefixes through the `prefix` event\n this.emit.bind(this, 'prefix'));\n\n // Implement Transform methods on top of parser\n this._transform = function (chunk, encoding, done) { parser.addChunk(chunk); done(); };\n this._flush = function (done) { parser.end(); done(); };\n}\nutil.inherits(N3StreamParser, Transform);\n\n// ## Exports\n// Export the `N3StreamParser` class as a whole.\nmodule.exports = N3StreamParser;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar inherits = require('inherits');\n\ninherits(Stream, EE);\nStream.Readable = require('readable-stream/readable.js');\nStream.Writable = require('readable-stream/writable.js');\nStream.Duplex = require('readable-stream/duplex.js');\nStream.Transform = require('readable-stream/transform.js');\nStream.PassThrough = require('readable-stream/passthrough.js');\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, unpipeInfo);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = require('events').EventEmitter;\n","'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/**/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n","// **N3StreamWriter** serializes a triple stream into an N3 stream\nvar Transform = require('stream').Transform,\n util = require('util'),\n N3Writer = require('./N3Writer.js');\n\n// ## Constructor\nfunction N3StreamWriter(options) {\n if (!(this instanceof N3StreamWriter))\n return new N3StreamWriter(options);\n\n // Initialize Transform base class\n Transform.call(this, { encoding: 'utf8' });\n this._writableState.objectMode = true;\n\n // Set up writer with a dummy stream object\n var self = this;\n var writer = new N3Writer({\n write: function (chunk, encoding, callback) { self.push(chunk); callback && callback(); },\n end: function (callback) { self.push(null); callback && callback(); },\n }, options);\n\n // Implement Transform methods on top of writer\n this._transform = function (triple, encoding, done) { writer.addTriple(triple, done); };\n this._flush = function (done) { writer.end(done); };\n}\nutil.inherits(N3StreamWriter, Transform);\n\n// ## Exports\n// Export the `N3StreamWriter` class as a whole.\nmodule.exports = N3StreamWriter;\n","'use strict'\nconst BlankNode = require('./blank-node')\nconst ClassOrder = require('./class-order')\nconst Collection = require('./collection')\nconst Literal = require('./literal')\nconst log = require('./log')\nconst NamedNode = require('./named-node')\nconst Node = require('./node')\nconst Serializer = require('./serialize')\nconst Statement = require('./statement')\nconst Variable = require('./variable')\n\nclass Formula extends Node {\n constructor (statements, constraints, initBindings, optional) {\n super()\n this.termType = Formula.termType\n this.statements = statements || []\n this.constraints = constraints || []\n this.initBindings = initBindings || []\n this.optional = optional || []\n }\n add (s, p, o, g) {\n return this.statements.push(new Statement(s, p, o, g))\n }\n addStatement (st) {\n return this.statements.push(st)\n }\n bnode (id) {\n return new BlankNode(id)\n }\n /**\n * Finds the types in the list which have no *stored* subtypes\n * These are a set of classes which provide by themselves complete\n * information -- the other classes are redundant for those who\n * know the class DAG.\n */\n bottomTypeURIs (types) {\n var bots\n var bottom\n var elt\n var i\n var k\n var len\n var ref\n var subs\n var v\n bots = []\n for (k in types) {\n if (!types.hasOwnProperty(k)) continue\n v = types[k]\n subs = this.each(void 0, this.sym('http://www.w3.org/2000/01/rdf-schema#subClassOf'), this.sym(k))\n bottom = true\n i = 0\n for (len = subs.length; i < len; i++) {\n elt = subs[i]\n ref = elt.uri\n if (ref in types) { // the subclass is one we know\n bottom = false\n break\n }\n }\n if (bottom) {\n bots[k] = v\n }\n }\n return bots\n }\n collection () {\n return new Collection()\n }\n each (s, p, o, g) {\n var elt, i, l, m, q\n var len, len1, len2, len3\n var results = []\n var sts = this.statementsMatching(s, p, o, g, false)\n if (s == null) {\n for (i = 0, len = sts.length; i < len; i++) {\n elt = sts[i]\n results.push(elt.subject)\n }\n } else if (p == null) {\n for (l = 0, len1 = sts.length; l < len1; l++) {\n elt = sts[l]\n results.push(elt.predicate)\n }\n } else if (o == null) {\n for (m = 0, len2 = sts.length; m < len2; m++) {\n elt = sts[m]\n results.push(elt.object)\n }\n } else if (g == null) {\n for (q = 0, len3 = sts.length; q < len3; q++) {\n elt = sts[q]\n results.push(elt.why)\n }\n }\n return results\n }\n equals (other) {\n if (!other) {\n return false\n }\n return this.hashString() === other.hashString()\n }\n /*\n For thisClass or any subclass, anything which has it is its type\n or is the object of something which has the type as its range, or subject\n of something which has the type as its domain\n We don't bother doing subproperty (yet?)as it doesn't seeem to be used much.\n Get all the Classes of which we can RDFS-infer the subject is a member\n @returns a hash of URIs\n */\n\n /**\n * For thisClass or any subclass, anything which has it is its type\n * or is the object of something which has the type as its range, or subject\n * of something which has the type as its domain\n * We don't bother doing subproperty (yet?)as it doesn't seeem to be used\n * much.\n * Get all the Classes of which we can RDFS-infer the subject is a member\n * @return a hash of URIs\n */\n findMembersNT (thisClass) {\n var i\n var l\n var len\n var len1\n var len2\n var len3\n var len4\n var m\n var members\n var pred\n var q\n var ref\n var ref1\n var ref2\n var ref3\n var ref4\n var ref5\n var seeds\n var st\n var t\n var u\n seeds = {}\n seeds[thisClass.toNT()] = true\n members = {}\n ref = this.transitiveClosure(seeds, this.sym('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true)\n for (t in ref) {\n if (!ref.hasOwnProperty(t)) continue\n ref1 = this.statementsMatching(void 0,\n this.sym('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),\n this.fromNT(t))\n for (i = 0, len = ref1.length; i < len; i++) {\n st = ref1[i]\n members[st.subject.toNT()] = st\n }\n ref2 = this.each(void 0,\n this.sym('http://www.w3.org/2000/01/rdf-schema#domain'),\n this.fromNT(t))\n for (l = 0, len1 = ref2.length; l < len1; l++) {\n pred = ref2[l]\n ref3 = this.statementsMatching(void 0, pred)\n for (m = 0, len2 = ref3.length; m < len2; m++) {\n st = ref3[m]\n members[st.subject.toNT()] = st\n }\n }\n ref4 = this.each(void 0,\n this.sym('http://www.w3.org/2000/01/rdf-schema#range'),\n this.fromNT(t))\n for (q = 0, len3 = ref4.length; q < len3; q++) {\n pred = ref4[q]\n ref5 = this.statementsMatching(void 0, pred)\n for (u = 0, len4 = ref5.length; u < len4; u++) {\n st = ref5[u]\n members[st.object.toNT()] = st\n }\n }\n }\n return members\n }\n findMemberURIs (subject) {\n return this.NTtoURI(this.findMembersNT(subject))\n }\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a superclass\n * Returns a hash table where key is NT of type and value is statement why we\n * think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n */\n findSubClassesNT (subject) {\n var types = {}\n types[subject.toNT()] = true\n return this.transitiveClosure(types,\n this.sym('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true)\n }\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a subclass\n * Returns a hash table where key is NT of type and value is statement why we\n * think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n */\n findSuperClassesNT (subject) {\n var types = {}\n types[subject.toNT()] = true\n return this.transitiveClosure(types,\n this.sym('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false)\n }\n /**\n * Get all the Classes of which we can RDFS-infer the subject is a member\n * todo: This will loop is there is a class subclass loop (Sublass loops are\n * not illegal)\n * Returns a hash table where key is NT of type and value is statement why we\n * think so.\n * Does NOT return terms, returns URI strings.\n * We use NT representations in this version because they handle blank nodes.\n */\n findTypesNT (subject) {\n var domain\n var i\n var l\n var len\n var len1\n var len2\n var len3\n var m\n var q\n var range\n var rdftype\n var ref\n var ref1\n var ref2\n var ref3\n var st\n var types\n rdftype = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'\n types = []\n ref = this.statementsMatching(subject, void 0, void 0)\n for (i = 0, len = ref.length; i < len; i++) {\n st = ref[i]\n if (st.predicate.uri === rdftype) {\n types[st.object.toNT()] = st\n } else {\n ref1 = this.each(st.predicate, this.sym('http://www.w3.org/2000/01/rdf-schema#domain'))\n for (l = 0, len1 = ref1.length; l < len1; l++) {\n range = ref1[l]\n types[range.toNT()] = st\n }\n }\n }\n ref2 = this.statementsMatching(void 0, void 0, subject)\n for (m = 0, len2 = ref2.length; m < len2; m++) {\n st = ref2[m]\n ref3 = this.each(st.predicate, this.sym('http://www.w3.org/2000/01/rdf-schema#range'))\n for (q = 0, len3 = ref3.length; q < len3; q++) {\n domain = ref3[q]\n types[domain.toNT()] = st\n }\n }\n return this.transitiveClosure(types, this.sym('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false)\n }\n findTypeURIs (subject) {\n return this.NTtoURI(this.findTypesNT(subject))\n }\n // Trace the statements which connect directly, or through bnodes\n // Returns an array of statements\n // doc param may be null to search all documents in store\n connectedStatements (subject, doc, excludePredicateURIs) {\n excludePredicateURIs = excludePredicateURIs || []\n var todo = [subject]\n var done = []\n var doneArcs = []\n var result = []\n var self = this\n var follow = function (x) {\n var queue = function (x) {\n if (x.termType === 'BlankNode' && !done[x.value]) {\n done[x.value] = true\n todo.push(x)\n }\n }\n var sts = self.statementsMatching(null, null, x, doc)\n .concat(self.statementsMatching(x, null, null, doc))\n sts = sts.filter(function (st) {\n if (excludePredicateURIs[st.predicate.uri]) return false\n var hash = st.toNT()\n if (doneArcs[hash]) return false\n doneArcs[hash] = true\n return true\n }\n )\n sts.forEach(function (st, i) {\n queue(st.subject)\n queue(st.object)\n })\n result = result.concat(sts)\n }\n while (todo.length) {\n follow(todo.shift())\n }\n // console.log('' + result.length + ' statements about ' + subject)\n return result\n }\n\n formula () {\n return new Formula()\n }\n /**\n * Transforms an NTriples string format into a Node.\n * The bnode bit should not be used on program-external values; designed\n * for internal work such as storing a bnode id in an HTML attribute.\n * This will only parse the strings generated by the vaious toNT() methods.\n */\n fromNT (str) {\n var dt, k, lang, x\n switch (str[0]) {\n case '<':\n return this.sym(str.slice(1, -1))\n case '\"':\n lang = void 0\n dt = void 0\n k = str.lastIndexOf('\"')\n if (k < str.length - 1) {\n if (str[k + 1] === '@') {\n lang = str.slice(k + 2)\n } else if (str.slice(k + 1, k + 3) === '^^') {\n dt = this.fromNT(str.slice(k + 3))\n } else {\n throw new Error(\"Can't convert string from NT: \" + str)\n }\n }\n str = str.slice(1, k)\n str = str.replace(/\\\\\"/g, '\"')\n str = str.replace(/\\\\n/g, '\\n')\n str = str.replace(/\\\\\\\\/g, '\\\\')\n return this.literal(str, lang, dt)\n case '_':\n return new BlankNode(str.slice(2))\n case '?':\n return new Variable(str.slice(1))\n }\n throw new Error(\"Can't convert from NT: \" + str)\n }\n\n holds (s, p, o, g) {\n var i\n if (arguments.length === 1) {\n if (!s) {\n return true\n }\n if (s instanceof Array) {\n for (i = 0; i < s.length; i++) {\n if (!this.holds(s[i])) {\n return false\n }\n }\n return true\n } else if (s instanceof Statement) {\n return this.holds(s.subject, s.predicate, s.object, s.why)\n } else if (s.statements) {\n return this.holds(s.statements)\n }\n }\n\n var st = this.anyStatementMatching(s, p, o, g)\n return st != null\n }\n holdsStatement (st) {\n return this.holds(st.subject, st.predicate, st.object, st.why)\n }\n list (values) {\n let collection = new Collection()\n values.forEach(function (val) {\n collection.append(val)\n })\n return collection\n }\n literal (val, lang, dt) {\n return new Literal('' + val, lang, dt)\n }\n /**\n * transform a collection of NTriple URIs into their URI strings\n * @param t some iterable colletion of NTriple URI strings\n * @return a collection of the URIs as strings\n * todo: explain why it is important to go through NT\n */\n NTtoURI (t) {\n var k, v\n var uris = {}\n for (k in t) {\n if (!t.hasOwnProperty(k)) continue\n v = t[k]\n if (k[0] === '<') {\n uris[k.slice(1, -1)] = v\n }\n }\n return uris\n }\n serialize (base, contentType, provenance) {\n var documentString\n var sts\n var sz\n sz = Serializer(this)\n sz.suggestNamespaces(this.namespaces)\n sz.setBase(base)\n if (provenance) {\n sts = this.statementsMatching(void 0, void 0, void 0, provenance)\n } else {\n sts = this.statements\n }\n switch (\n contentType != null ? contentType : 'text/n3') {\n case 'application/rdf+xml':\n documentString = sz.statementsToXML(sts)\n break\n case 'text/n3':\n case 'text/turtle':\n documentString = sz.statementsToN3(sts)\n break\n default:\n throw new Error('serialize: Content-type ' + contentType +\n ' not supported.')\n }\n return documentString\n }\n substitute (bindings) {\n var statementsCopy = this.statements.map(function (ea) {\n return ea.substitute(bindings)\n })\n console.log('Formula subs statmnts:' + statementsCopy)\n var y = new Formula()\n y.add(statementsCopy)\n console.log('indexed-form subs formula:' + y)\n return y\n }\n sym (uri, name) {\n if (name) {\n throw new Error('This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.')\n }\n return new NamedNode(uri)\n }\n the (s, p, o, g) {\n var x = this.any(s, p, o, g)\n if (x == null) {\n log.error('No value found for the() {' + s + ' ' + p + ' ' + o + '}.')\n }\n return x\n }\n /**\n * RDFS Inference\n * These are hand-written implementations of a backward-chaining reasoner\n * over the RDFS axioms.\n * @param seeds {Object} a hash of NTs of classes to start with\n * @param predicate The property to trace though\n * @param inverse trace inverse direction\n */\n transitiveClosure (seeds, predicate, inverse) {\n var elt, i, len, s, sups, t\n var agenda = {}\n Object.assign(agenda, seeds) // make a copy\n var done = {} // classes we have looked up\n while (true) {\n t = (function () {\n for (var p in agenda) {\n if (!agenda.hasOwnProperty(p)) continue\n return p\n }\n })()\n if (t == null) {\n return done\n }\n sups = inverse ? this.each(void 0, predicate, this.fromNT(t)) : this.each(this.fromNT(t), predicate)\n for (i = 0, len = sups.length; i < len; i++) {\n elt = sups[i]\n s = elt.toNT()\n if (s in done) {\n continue\n }\n if (s in agenda) {\n continue\n }\n agenda[s] = agenda[t]\n }\n done[t] = agenda[t]\n delete agenda[t]\n }\n }\n /**\n * Finds the types in the list which have no *stored* supertypes\n * We exclude the universal class, owl:Things and rdf:Resource, as it is\n * information-free.\n */\n topTypeURIs (types) {\n var i\n var j\n var k\n var len\n var n\n var ref\n var tops\n var v\n tops = []\n for (k in types) {\n if (!types.hasOwnProperty(k)) continue\n v = types[k]\n n = 0\n ref = this.each(this.sym(k), this.sym('http://www.w3.org/2000/01/rdf-schema#subClassOf'))\n for (i = 0, len = ref.length; i < len; i++) {\n j = ref[i]\n if (j.uri !== 'http://www.w3.org/2000/01/rdf-schema#Resource') {\n n++\n break\n }\n }\n if (!n) {\n tops[k] = v\n }\n }\n if (tops['http://www.w3.org/2000/01/rdf-schema#Resource']) {\n delete tops['http://www.w3.org/2000/01/rdf-schema#Resource']\n }\n if (tops['http://www.w3.org/2002/07/owl#Thing']) {\n delete tops['http://www.w3.org/2002/07/owl#Thing']\n }\n return tops\n }\n toString () {\n return '{' + this.statements.join('\\n') + '}'\n }\n whether (s, p, o, g) {\n return this.statementsMatching(s, p, o, g, false).length\n }\n}\nFormula.termType = 'Graph'\n\nFormula.prototype.classOrder = ClassOrder['Graph']\nFormula.prototype.isVar = 0\n\nFormula.prototype.ns = require('./namespace')\nFormula.prototype.variable = name => new Variable(name)\n\nmodule.exports = Formula\n","module.exports = parse\n\nconst BlankNode = require('./blank-node')\nconst jsonld = require('jsonld')\nconst Literal = require('./literal')\nconst N3 = require('n3') // @@ Goal: remove this dependency\nconst N3Parser = require('./n3parser')\nconst NamedNode = require('./named-node')\nconst parseRDFaDOM = require('./rdfaparser').parseRDFaDOM\nconst RDFParser = require('./rdfxmlparser')\nconst sparqlUpdateParser = require('./patch-parser')\nconst Util = require('./util')\n\n/**\n * Parse a string and put the result into the graph kb.\n * Normal method is sync.\n * Unfortunately jsdonld is currently written to need to be called async.\n * Hence the mess below with executeCallback.\n */\nfunction parse (str, kb, base, contentType, callback) {\n contentType = contentType || 'text/turtle'\n contentType = contentType.split(';')[0]\n try {\n if (contentType === 'text/n3' || contentType === 'text/turtle') {\n var p = N3Parser(kb, kb, base, base, null, null, '', null)\n p.loadBuf(str)\n executeCallback()\n } else if (contentType === 'application/rdf+xml') {\n var parser = new RDFParser(kb)\n parser.parse(Util.parseXML(str), base, kb.sym(base))\n executeCallback()\n } else if (contentType === 'application/xhtml+xml') {\n parseRDFaDOM(Util.parseXML(str, {contentType: 'application/xhtml+xml'}), kb, base)\n executeCallback()\n } else if (contentType === 'text/html') {\n parseRDFaDOM(Util.parseXML(str, {contentType: 'text/html'}), kb, base)\n executeCallback()\n } else if (contentType === 'application/sparql-update') { // @@ we handle a subset\n sparqlUpdateParser(str, kb, base)\n executeCallback()\n } else if (contentType === 'application/ld+json' ||\n contentType === 'application/nquads' ||\n contentType === 'application/n-quads') {\n var n3Parser = N3.Parser()\n var triples = []\n if (contentType === 'application/ld+json') {\n var jsonDocument\n try {\n jsonDocument = JSON.parse(str)\n } catch (parseErr) {\n return callback(parseErr, null)\n }\n jsonld.toRDF(jsonDocument,\n {format: 'application/nquads', base},\n nquadCallback)\n } else {\n nquadCallback(null, str)\n }\n } else {\n throw new Error(\"Don't know how to parse \" + contentType + ' yet')\n }\n } catch (e) {\n executeErrorCallback(e)\n }\n\n function executeCallback () {\n if (callback) {\n callback(null, kb)\n } else {\n return\n }\n }\n\n function executeErrorCallback (e) {\n if (contentType !== 'application/ld+json' ||\n contentType !== 'application/nquads' ||\n contentType !== 'application/n-quads') {\n if (callback) {\n callback(e, kb)\n } else {\n throw new Error('Error trying to parse <' + base + '> as ' +\n contentType + ':\\n' + e + ':\\n' + e.stack)\n }\n }\n }\n/*\n function setJsonLdBase (doc, base) {\n if (doc instanceof Array) {\n return\n }\n if (!('@context' in doc)) {\n doc['@context'] = {}\n }\n doc['@context']['@base'] = base\n }\n*/\n function nquadCallback (err, nquads) {\n if (err) {\n callback(err, kb)\n }\n try {\n n3Parser.parse(nquads, tripleCallback)\n } catch (err) {\n callback(err, kb)\n }\n }\n\n function tripleCallback (err, triple, prefixes) {\n if (err) {\n callback(err, kb)\n }\n if (triple) {\n triples.push(triple)\n } else {\n for (var i = 0; i < triples.length; i++) {\n addTriple(kb, triples[i])\n }\n callback(null, kb)\n }\n }\n\n function addTriple (kb, triple) {\n var subject = createTerm(triple.subject)\n var predicate = createTerm(triple.predicate)\n var object = createTerm(triple.object)\n var why = null\n if (triple.graph) {\n why = createTerm(triple.graph)\n }\n kb.add(subject, predicate, object, why)\n }\n\n function createTerm (termString) {\n var value\n if (N3.Util.isLiteral(termString)) {\n value = N3.Util.getLiteralValue(termString)\n var language = N3.Util.getLiteralLanguage(termString)\n var datatype = new NamedNode(N3.Util.getLiteralType(termString))\n return new Literal(value, language, datatype)\n } else if (N3.Util.isIRI(termString)) {\n return new NamedNode(termString)\n } else if (N3.Util.isBlank(termString)) {\n value = termString.substring(2, termString.length)\n return new BlankNode(value)\n } else {\n return null\n }\n }\n}\n","// Parse a simple SPARL-Update subset syntax for patches.\n//\n// This parses\n// WHERE {xxx} DELETE {yyy} INSERT DATA {zzz}\n// (not necessarily in that order)\n// as though it were the n3\n// <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}.\nmodule.exports = sparqlUpdateParser\n\nconst N3Parser = require('./n3parser')\nconst Namespace = require('./namespace')\n\nfunction sparqlUpdateParser (str, kb, base) {\n var i, j, k\n var keywords = [ 'INSERT', 'DELETE', 'WHERE' ]\n var SQNS = Namespace('http://www.w3.org/ns/pim/patch#')\n var p = N3Parser(kb, kb, base, base, null, null, '', null)\n var clauses = {}\n\n var badSyntax = function (uri, lines, str, i, why) {\n return ('Line ' + (lines + 1) + ' of <' + uri + '>: Bad syntax:\\n ' +\n why + '\\n at: \"' + str.slice(i, (i + 30)) + '\"')\n }\n\n // var check = function (next, last, message) {\n // if (next < 0) {\n // throw badSyntax(p._thisDoc, p.lines, str, j, last, message)\n // }\n // return next\n // }\n i = 0\n var query = kb.sym(base + '#query') // Invent a URI for the query\n clauses['query'] = query // A way of accessing it in its N3 model.\n\n while (true) {\n // console.log(\"A Now at i = \" + i)\n j = p.skipSpace(str, i)\n if (j < 0) {\n return clauses\n }\n // console.log(\"B After space at j= \" + j)\n if (str[j] === ';') {\n i = p.skipSpace(str, j + 1)\n if (i < 0) {\n return clauses // Allow end in a\n }\n j = i\n }\n var found = false\n for (k = 0; k < keywords.length; k++) {\n var key = keywords[k]\n if (str.slice(j, j + key.length) === key) {\n i = p.skipSpace(str, j + key.length)\n if (i < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, j + key.length, 'found EOF, needed {...} after ' + key)\n }\n if (((key === 'INSERT') || (key === 'DELETE')) && str.slice(i, i + 4) === 'DATA') { // Some wanted 'DATA'. Whatever\n j = p.skipSpace(str, i + 4)\n if (j < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, i + 4, 'needed {...} after INSERT DATA ' + key)\n }\n i = j\n }\n var res2 = []\n j = p.node(str, i, res2) // Parse all the complexity of the clause\n\n if (j < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, i,\n 'bad syntax or EOF in {...} after ' + key)\n }\n clauses[key.toLowerCase()] = res2[0]\n kb.add(query, SQNS(key.toLowerCase()), res2[0]) // , kb.sym(base)\n // key is the keyword and res2 has the contents\n found = true\n i = j\n }\n }\n if (!found && str.slice(j, j + 7) === '@prefix') {\n i = p.directive(str, j)\n if (i < 0) {\n throw badSyntax(p._thisDoc, p.lines, str, i,\n 'bad syntax or EOF after @prefix ')\n }\n // console.log(\"P before dot i= \" + i)\n i = p.checkDot(str, i)\n // console.log(\"Q after dot i= \" + i)\n found = true\n }\n if (!found) {\n // console.log(\"Bad syntax \" + j)\n throw badSyntax(p._thisDoc, p.lines, str, j,\n \"Unknown syntax at start of statememt: '\" + str.slice(j).slice(0, 20) + \"'\")\n }\n } // while\n// return clauses\n}\n","/*\n * Updates-Via\n */\nconst namedNode = require('./data-factory').namedNode\n\nclass UpdatesSocket {\n constructor (parent, via) {\n this.parent = parent\n this.via = via\n this.connected = false\n this.pending = {}\n this.subscribed = {}\n this.socket = {}\n try {\n this.socket = new WebSocket(via)\n this.socket.onopen = this.onOpen\n this.socket.onclose = this.onClose\n this.socket.onmessage = this.onMessage\n this.socket.onerror = this.onError\n } catch (error) {\n this.onError(error)\n }\n }\n _decode (q) {\n var elt\n var i\n var k\n var r\n var ref\n var ref1\n var v\n r = {}\n ref = (function () {\n var j, len, ref, results\n ref = q.split('&')\n results = []\n for (j = 0, len = ref.length; j < len; j++) {\n elt = ref[j]\n results.push(elt.split('='))\n }\n return results\n })()\n for (i in ref) {\n elt = ref[i]\n ref1 = [decodeURIComponent(elt[0]), decodeURIComponent(elt[1])]\n k = ref1[0]\n v = ref1[1]\n if (r[k] == null) {\n r[k] = []\n }\n r[k].push(v)\n }\n return r\n }\n _send (method, uri, data) {\n var base, message\n message = [method, uri, data].join(' ')\n return typeof (base = this.socket).send === 'function' ? base.send(message) : void 0\n }\n _subscribe (uri) {\n this._send('sub', uri, '')\n this.subscribed[uri] = true\n return this.subscribed[uri]\n }\n onClose (e) {\n var uri\n this.connected = false\n for (uri in this.subscribed) {\n this.pending[uri] = true\n }\n this.subscribed = {}\n return this.subscribed\n }\n onError (e) {\n throw new Error('onError' + e)\n }\n onMessage (e) {\n var base, message\n message = e.data.split(' ')\n if (message[0] === 'ping') {\n return typeof (base = this.socket).send === 'function' ? base.send('pong ' + message.slice(1).join(' ')) : void 0\n } else if (message[0] === 'pub') {\n return this.parent.onUpdate(message[1], this._decode(message[2]))\n }\n }\n onOpen (e) {\n var results, uri\n this.connected = true\n results = []\n for (uri in this.pending) {\n delete this.pending[uri]\n results.push(this._subscribe(uri))\n }\n return results\n }\n subscribe (uri) {\n if (this.connected) {\n return this._subscribe(uri)\n } else {\n this.pending[uri] = true\n return this.pending[uri]\n }\n }\n}\n\nclass UpdatesVia {\n constructor (fetcher) {\n this.fetcher = fetcher\n this.graph = {}\n this.via = {}\n this.fetcher.addCallback('headers', this.onHeaders)\n }\n onHeaders (d) {\n var etag, uri, via\n if (d.headers == null) {\n return true\n }\n if (typeof WebSocket === 'undefined' || WebSocket === null) {\n return true\n }\n etag = d.headers['etag']\n via = d.headers['updates-via']\n uri = d.uri\n if (etag && via) {\n this.graph[uri] = {\n etag: etag,\n via: via\n }\n this.register(via, uri)\n }\n return true\n }\n onUpdate (uri, d) {\n return this.fetcher.refresh(namedNode(uri))\n }\n register (via, uri) {\n if (this.via[via] == null) {\n this.via[via] = new UpdatesSocket(this, via)\n }\n return this.via[via].subscribe(uri)\n }\n}\n\nmodule.exports.UpdatesSocket = UpdatesSocket\nmodule.exports.UpdatesVia = UpdatesVia\n","var $rdf = {\n BlankNode: require('./blank-node'),\n Collection: require('./collection'),\n convert: require('./convert'),\n DataFactory: require('./data-factory'),\n Empty: require('./empty'),\n Fetcher: require('./fetcher'),\n Formula: require('./formula'),\n IndexedFormula: require('./indexed-formula'),\n jsonParser: require('./jsonparser'),\n Literal: require('./literal'),\n log: require('./log'),\n N3Parser: require('./n3parser'),\n NamedNode: require('./named-node'),\n Namespace: require('./namespace'),\n Node: require('./node'),\n parse: require('./parse'),\n Query: require('./query').Query,\n queryToSPARQL: require('./query-to-sparql'),\n RDFaProcessor: require('./rdfaparser'),\n RDFParser: require('./rdfxmlparser'),\n serialize: require('./serialize'),\n Serializer: require('./serializer'),\n SPARQLToQuery: require('./sparql-to-query'),\n sparqlUpdateParser: require('./patch-parser'),\n Statement: require('./statement'),\n term: require('./node').fromValue,\n UpdateManager: require('./update-manager'),\n UpdatesSocket: require('./updates-via').UpdatesSocket,\n UpdatesVia: require('./updates-via').UpdatesVia,\n uri: require('./uri'),\n Util: require('./util'),\n Variable: require('./variable')\n}\n\n$rdf.NextId = $rdf.BlankNode.nextId\n\n$rdf.fromNT = $rdf.Formula.prototype.fromNT\n$rdf.fetcher = $rdf.DataFactory.fetcher\n$rdf.graph = $rdf.DataFactory.graph\n$rdf.lit = $rdf.DataFactory.lit\n$rdf.st = $rdf.DataFactory.st\n$rdf.sym = $rdf.DataFactory.namedNode\n$rdf.variable = $rdf.DataFactory.variable\n\n// RDFJS DataFactory interface\n$rdf.blankNode = $rdf.DataFactory.blankNode\n$rdf.defaultGraph = $rdf.DataFactory.defaultGraph\n$rdf.literal = $rdf.DataFactory.literal\n$rdf.namedNode = $rdf.DataFactory.namedNode\n$rdf.quad = $rdf.DataFactory.quad\n$rdf.triple = $rdf.DataFactory.triple\n\nmodule.exports = $rdf\n","/*!\n * async\n * https://github.com/caolan/async\n *\n * Copyright 2010-2014 Caolan McMahon\n * Released under the MIT license\n */\n/*jshint onevar: false, indent:4 */\n/*global setImmediate: false, setTimeout: false, console: false */\n(function () {\n\n var async = {};\n\n // global on the server, window in the browser\n var root, previous_async;\n\n root = this;\n if (root != null) {\n previous_async = root.async;\n }\n\n async.noConflict = function () {\n root.async = previous_async;\n return async;\n };\n\n function only_once(fn) {\n var called = false;\n return function() {\n if (called) throw new Error(\"Callback was already called.\");\n called = true;\n fn.apply(root, arguments);\n }\n }\n\n //// cross-browser compatiblity functions ////\n\n var _toString = Object.prototype.toString;\n\n var _isArray = Array.isArray || function (obj) {\n return _toString.call(obj) === '[object Array]';\n };\n\n var _each = function (arr, iterator) {\n for (var i = 0; i < arr.length; i += 1) {\n iterator(arr[i], i, arr);\n }\n };\n\n var _map = function (arr, iterator) {\n if (arr.map) {\n return arr.map(iterator);\n }\n var results = [];\n _each(arr, function (x, i, a) {\n results.push(iterator(x, i, a));\n });\n return results;\n };\n\n var _reduce = function (arr, iterator, memo) {\n if (arr.reduce) {\n return arr.reduce(iterator, memo);\n }\n _each(arr, function (x, i, a) {\n memo = iterator(memo, x, i, a);\n });\n return memo;\n };\n\n var _keys = function (obj) {\n if (Object.keys) {\n return Object.keys(obj);\n }\n var keys = [];\n for (var k in obj) {\n if (obj.hasOwnProperty(k)) {\n keys.push(k);\n }\n }\n return keys;\n };\n\n //// exported async module functions ////\n\n //// nextTick implementation with browser-compatible fallback ////\n if (typeof process === 'undefined' || !(process.nextTick)) {\n if (typeof setImmediate === 'function') {\n async.nextTick = function (fn) {\n // not a direct alias for IE10 compatibility\n setImmediate(fn);\n };\n async.setImmediate = async.nextTick;\n }\n else {\n async.nextTick = function (fn) {\n setTimeout(fn, 0);\n };\n async.setImmediate = async.nextTick;\n }\n }\n else {\n async.nextTick = process.nextTick;\n if (typeof setImmediate !== 'undefined') {\n async.setImmediate = function (fn) {\n // not a direct alias for IE10 compatibility\n setImmediate(fn);\n };\n }\n else {\n async.setImmediate = async.nextTick;\n }\n }\n\n async.each = function (arr, iterator, callback) {\n callback = callback || function () {};\n if (!arr.length) {\n return callback();\n }\n var completed = 0;\n _each(arr, function (x) {\n iterator(x, only_once(done) );\n });\n function done(err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n completed += 1;\n if (completed >= arr.length) {\n callback();\n }\n }\n }\n };\n async.forEach = async.each;\n\n async.eachSeries = function (arr, iterator, callback) {\n callback = callback || function () {};\n if (!arr.length) {\n return callback();\n }\n var completed = 0;\n var iterate = function () {\n iterator(arr[completed], function (err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n completed += 1;\n if (completed >= arr.length) {\n callback();\n }\n else {\n iterate();\n }\n }\n });\n };\n iterate();\n };\n async.forEachSeries = async.eachSeries;\n\n async.eachLimit = function (arr, limit, iterator, callback) {\n var fn = _eachLimit(limit);\n fn.apply(null, [arr, iterator, callback]);\n };\n async.forEachLimit = async.eachLimit;\n\n var _eachLimit = function (limit) {\n\n return function (arr, iterator, callback) {\n callback = callback || function () {};\n if (!arr.length || limit <= 0) {\n return callback();\n }\n var completed = 0;\n var started = 0;\n var running = 0;\n\n (function replenish () {\n if (completed >= arr.length) {\n return callback();\n }\n\n while (running < limit && started < arr.length) {\n started += 1;\n running += 1;\n iterator(arr[started - 1], function (err) {\n if (err) {\n callback(err);\n callback = function () {};\n }\n else {\n completed += 1;\n running -= 1;\n if (completed >= arr.length) {\n callback();\n }\n else {\n replenish();\n }\n }\n });\n }\n })();\n };\n };\n\n\n var doParallel = function (fn) {\n return function () {\n var args = Array.prototype.slice.call(arguments);\n return fn.apply(null, [async.each].concat(args));\n };\n };\n var doParallelLimit = function(limit, fn) {\n return function () {\n var args = Array.prototype.slice.call(arguments);\n return fn.apply(null, [_eachLimit(limit)].concat(args));\n };\n };\n var doSeries = function (fn) {\n return function () {\n var args = Array.prototype.slice.call(arguments);\n return fn.apply(null, [async.eachSeries].concat(args));\n };\n };\n\n\n var _asyncMap = function (eachfn, arr, iterator, callback) {\n arr = _map(arr, function (x, i) {\n return {index: i, value: x};\n });\n if (!callback) {\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (err) {\n callback(err);\n });\n });\n } else {\n var results = [];\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (err, v) {\n results[x.index] = v;\n callback(err);\n });\n }, function (err) {\n callback(err, results);\n });\n }\n };\n async.map = doParallel(_asyncMap);\n async.mapSeries = doSeries(_asyncMap);\n async.mapLimit = function (arr, limit, iterator, callback) {\n return _mapLimit(limit)(arr, iterator, callback);\n };\n\n var _mapLimit = function(limit) {\n return doParallelLimit(limit, _asyncMap);\n };\n\n // reduce only has a series version, as doing reduce in parallel won't\n // work in many situations.\n async.reduce = function (arr, memo, iterator, callback) {\n async.eachSeries(arr, function (x, callback) {\n iterator(memo, x, function (err, v) {\n memo = v;\n callback(err);\n });\n }, function (err) {\n callback(err, memo);\n });\n };\n // inject alias\n async.inject = async.reduce;\n // foldl alias\n async.foldl = async.reduce;\n\n async.reduceRight = function (arr, memo, iterator, callback) {\n var reversed = _map(arr, function (x) {\n return x;\n }).reverse();\n async.reduce(reversed, memo, iterator, callback);\n };\n // foldr alias\n async.foldr = async.reduceRight;\n\n var _filter = function (eachfn, arr, iterator, callback) {\n var results = [];\n arr = _map(arr, function (x, i) {\n return {index: i, value: x};\n });\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (v) {\n if (v) {\n results.push(x);\n }\n callback();\n });\n }, function (err) {\n callback(_map(results.sort(function (a, b) {\n return a.index - b.index;\n }), function (x) {\n return x.value;\n }));\n });\n };\n async.filter = doParallel(_filter);\n async.filterSeries = doSeries(_filter);\n // select alias\n async.select = async.filter;\n async.selectSeries = async.filterSeries;\n\n var _reject = function (eachfn, arr, iterator, callback) {\n var results = [];\n arr = _map(arr, function (x, i) {\n return {index: i, value: x};\n });\n eachfn(arr, function (x, callback) {\n iterator(x.value, function (v) {\n if (!v) {\n results.push(x);\n }\n callback();\n });\n }, function (err) {\n callback(_map(results.sort(function (a, b) {\n return a.index - b.index;\n }), function (x) {\n return x.value;\n }));\n });\n };\n async.reject = doParallel(_reject);\n async.rejectSeries = doSeries(_reject);\n\n var _detect = function (eachfn, arr, iterator, main_callback) {\n eachfn(arr, function (x, callback) {\n iterator(x, function (result) {\n if (result) {\n main_callback(x);\n main_callback = function () {};\n }\n else {\n callback();\n }\n });\n }, function (err) {\n main_callback();\n });\n };\n async.detect = doParallel(_detect);\n async.detectSeries = doSeries(_detect);\n\n async.some = function (arr, iterator, main_callback) {\n async.each(arr, function (x, callback) {\n iterator(x, function (v) {\n if (v) {\n main_callback(true);\n main_callback = function () {};\n }\n callback();\n });\n }, function (err) {\n main_callback(false);\n });\n };\n // any alias\n async.any = async.some;\n\n async.every = function (arr, iterator, main_callback) {\n async.each(arr, function (x, callback) {\n iterator(x, function (v) {\n if (!v) {\n main_callback(false);\n main_callback = function () {};\n }\n callback();\n });\n }, function (err) {\n main_callback(true);\n });\n };\n // all alias\n async.all = async.every;\n\n async.sortBy = function (arr, iterator, callback) {\n async.map(arr, function (x, callback) {\n iterator(x, function (err, criteria) {\n if (err) {\n callback(err);\n }\n else {\n callback(null, {value: x, criteria: criteria});\n }\n });\n }, function (err, results) {\n if (err) {\n return callback(err);\n }\n else {\n var fn = function (left, right) {\n var a = left.criteria, b = right.criteria;\n return a < b ? -1 : a > b ? 1 : 0;\n };\n callback(null, _map(results.sort(fn), function (x) {\n return x.value;\n }));\n }\n });\n };\n\n async.auto = function (tasks, callback) {\n callback = callback || function () {};\n var keys = _keys(tasks);\n var remainingTasks = keys.length\n if (!remainingTasks) {\n return callback();\n }\n\n var results = {};\n\n var listeners = [];\n var addListener = function (fn) {\n listeners.unshift(fn);\n };\n var removeListener = function (fn) {\n for (var i = 0; i < listeners.length; i += 1) {\n if (listeners[i] === fn) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n var taskComplete = function () {\n remainingTasks--\n _each(listeners.slice(0), function (fn) {\n fn();\n });\n };\n\n addListener(function () {\n if (!remainingTasks) {\n var theCallback = callback;\n // prevent final callback from calling itself if it errors\n callback = function () {};\n\n theCallback(null, results);\n }\n });\n\n _each(keys, function (k) {\n var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];\n var taskCallback = function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n if (err) {\n var safeResults = {};\n _each(_keys(results), function(rkey) {\n safeResults[rkey] = results[rkey];\n });\n safeResults[k] = args;\n callback(err, safeResults);\n // stop subsequent errors hitting callback multiple times\n callback = function () {};\n }\n else {\n results[k] = args;\n async.setImmediate(taskComplete);\n }\n };\n var requires = task.slice(0, Math.abs(task.length - 1)) || [];\n var ready = function () {\n return _reduce(requires, function (a, x) {\n return (a && results.hasOwnProperty(x));\n }, true) && !results.hasOwnProperty(k);\n };\n if (ready()) {\n task[task.length - 1](taskCallback, results);\n }\n else {\n var listener = function () {\n if (ready()) {\n removeListener(listener);\n task[task.length - 1](taskCallback, results);\n }\n };\n addListener(listener);\n }\n });\n };\n\n async.retry = function(times, task, callback) {\n var DEFAULT_TIMES = 5;\n var attempts = [];\n // Use defaults if times not passed\n if (typeof times === 'function') {\n callback = task;\n task = times;\n times = DEFAULT_TIMES;\n }\n // Make sure times is a number\n times = parseInt(times, 10) || DEFAULT_TIMES;\n var wrappedTask = function(wrappedCallback, wrappedResults) {\n var retryAttempt = function(task, finalAttempt) {\n return function(seriesCallback) {\n task(function(err, result){\n seriesCallback(!err || finalAttempt, {err: err, result: result});\n }, wrappedResults);\n };\n };\n while (times) {\n attempts.push(retryAttempt(task, !(times-=1)));\n }\n async.series(attempts, function(done, data){\n data = data[data.length - 1];\n (wrappedCallback || callback)(data.err, data.result);\n });\n }\n // If a callback is passed, run this as a controll flow\n return callback ? wrappedTask() : wrappedTask\n };\n\n async.waterfall = function (tasks, callback) {\n callback = callback || function () {};\n if (!_isArray(tasks)) {\n var err = new Error('First argument to waterfall must be an array of functions');\n return callback(err);\n }\n if (!tasks.length) {\n return callback();\n }\n var wrapIterator = function (iterator) {\n return function (err) {\n if (err) {\n callback.apply(null, arguments);\n callback = function () {};\n }\n else {\n var args = Array.prototype.slice.call(arguments, 1);\n var next = iterator.next();\n if (next) {\n args.push(wrapIterator(next));\n }\n else {\n args.push(callback);\n }\n async.setImmediate(function () {\n iterator.apply(null, args);\n });\n }\n };\n };\n wrapIterator(async.iterator(tasks))();\n };\n\n var _parallel = function(eachfn, tasks, callback) {\n callback = callback || function () {};\n if (_isArray(tasks)) {\n eachfn.map(tasks, function (fn, callback) {\n if (fn) {\n fn(function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n callback.call(null, err, args);\n });\n }\n }, callback);\n }\n else {\n var results = {};\n eachfn.each(_keys(tasks), function (k, callback) {\n tasks[k](function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n results[k] = args;\n callback(err);\n });\n }, function (err) {\n callback(err, results);\n });\n }\n };\n\n async.parallel = function (tasks, callback) {\n _parallel({ map: async.map, each: async.each }, tasks, callback);\n };\n\n async.parallelLimit = function(tasks, limit, callback) {\n _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);\n };\n\n async.series = function (tasks, callback) {\n callback = callback || function () {};\n if (_isArray(tasks)) {\n async.mapSeries(tasks, function (fn, callback) {\n if (fn) {\n fn(function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n callback.call(null, err, args);\n });\n }\n }, callback);\n }\n else {\n var results = {};\n async.eachSeries(_keys(tasks), function (k, callback) {\n tasks[k](function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (args.length <= 1) {\n args = args[0];\n }\n results[k] = args;\n callback(err);\n });\n }, function (err) {\n callback(err, results);\n });\n }\n };\n\n async.iterator = function (tasks) {\n var makeCallback = function (index) {\n var fn = function () {\n if (tasks.length) {\n tasks[index].apply(null, arguments);\n }\n return fn.next();\n };\n fn.next = function () {\n return (index < tasks.length - 1) ? makeCallback(index + 1): null;\n };\n return fn;\n };\n return makeCallback(0);\n };\n\n async.apply = function (fn) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function () {\n return fn.apply(\n null, args.concat(Array.prototype.slice.call(arguments))\n );\n };\n };\n\n var _concat = function (eachfn, arr, fn, callback) {\n var r = [];\n eachfn(arr, function (x, cb) {\n fn(x, function (err, y) {\n r = r.concat(y || []);\n cb(err);\n });\n }, function (err) {\n callback(err, r);\n });\n };\n async.concat = doParallel(_concat);\n async.concatSeries = doSeries(_concat);\n\n async.whilst = function (test, iterator, callback) {\n if (test()) {\n iterator(function (err) {\n if (err) {\n return callback(err);\n }\n async.whilst(test, iterator, callback);\n });\n }\n else {\n callback();\n }\n };\n\n async.doWhilst = function (iterator, test, callback) {\n iterator(function (err) {\n if (err) {\n return callback(err);\n }\n var args = Array.prototype.slice.call(arguments, 1);\n if (test.apply(null, args)) {\n async.doWhilst(iterator, test, callback);\n }\n else {\n callback();\n }\n });\n };\n\n async.until = function (test, iterator, callback) {\n if (!test()) {\n iterator(function (err) {\n if (err) {\n return callback(err);\n }\n async.until(test, iterator, callback);\n });\n }\n else {\n callback();\n }\n };\n\n async.doUntil = function (iterator, test, callback) {\n iterator(function (err) {\n if (err) {\n return callback(err);\n }\n var args = Array.prototype.slice.call(arguments, 1);\n if (!test.apply(null, args)) {\n async.doUntil(iterator, test, callback);\n }\n else {\n callback();\n }\n });\n };\n\n async.queue = function (worker, concurrency) {\n if (concurrency === undefined) {\n concurrency = 1;\n }\n function _insert(q, data, pos, callback) {\n if (!q.started){\n q.started = true;\n }\n if (!_isArray(data)) {\n data = [data];\n }\n if(data.length == 0) {\n // call drain immediately if there are no tasks\n return async.setImmediate(function() {\n if (q.drain) {\n q.drain();\n }\n });\n }\n _each(data, function(task) {\n var item = {\n data: task,\n callback: typeof callback === 'function' ? callback : null\n };\n\n if (pos) {\n q.tasks.unshift(item);\n } else {\n q.tasks.push(item);\n }\n\n if (q.saturated && q.tasks.length === q.concurrency) {\n q.saturated();\n }\n async.setImmediate(q.process);\n });\n }\n\n var workers = 0;\n var q = {\n tasks: [],\n concurrency: concurrency,\n saturated: null,\n empty: null,\n drain: null,\n started: false,\n paused: false,\n push: function (data, callback) {\n _insert(q, data, false, callback);\n },\n kill: function () {\n q.drain = null;\n q.tasks = [];\n },\n unshift: function (data, callback) {\n _insert(q, data, true, callback);\n },\n process: function () {\n if (!q.paused && workers < q.concurrency && q.tasks.length) {\n var task = q.tasks.shift();\n if (q.empty && q.tasks.length === 0) {\n q.empty();\n }\n workers += 1;\n var next = function () {\n workers -= 1;\n if (task.callback) {\n task.callback.apply(task, arguments);\n }\n if (q.drain && q.tasks.length + workers === 0) {\n q.drain();\n }\n q.process();\n };\n var cb = only_once(next);\n worker(task.data, cb);\n }\n },\n length: function () {\n return q.tasks.length;\n },\n running: function () {\n return workers;\n },\n idle: function() {\n return q.tasks.length + workers === 0;\n },\n pause: function () {\n if (q.paused === true) { return; }\n q.paused = true;\n },\n resume: function () {\n if (q.paused === false) { return; }\n q.paused = false;\n // Need to call q.process once per concurrent\n // worker to preserve full concurrency after pause\n for (var w = 1; w <= q.concurrency; w++) {\n async.setImmediate(q.process);\n }\n }\n };\n return q;\n };\n\n async.priorityQueue = function (worker, concurrency) {\n\n function _compareTasks(a, b){\n return a.priority - b.priority;\n };\n\n function _binarySearch(sequence, item, compare) {\n var beg = -1,\n end = sequence.length - 1;\n while (beg < end) {\n var mid = beg + ((end - beg + 1) >>> 1);\n if (compare(item, sequence[mid]) >= 0) {\n beg = mid;\n } else {\n end = mid - 1;\n }\n }\n return beg;\n }\n\n function _insert(q, data, priority, callback) {\n if (!q.started){\n q.started = true;\n }\n if (!_isArray(data)) {\n data = [data];\n }\n if(data.length == 0) {\n // call drain immediately if there are no tasks\n return async.setImmediate(function() {\n if (q.drain) {\n q.drain();\n }\n });\n }\n _each(data, function(task) {\n var item = {\n data: task,\n priority: priority,\n callback: typeof callback === 'function' ? callback : null\n };\n\n q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);\n\n if (q.saturated && q.tasks.length === q.concurrency) {\n q.saturated();\n }\n async.setImmediate(q.process);\n });\n }\n\n // Start with a normal queue\n var q = async.queue(worker, concurrency);\n\n // Override push to accept second parameter representing priority\n q.push = function (data, priority, callback) {\n _insert(q, data, priority, callback);\n };\n\n // Remove unshift function\n delete q.unshift;\n\n return q;\n };\n\n async.cargo = function (worker, payload) {\n var working = false,\n tasks = [];\n\n var cargo = {\n tasks: tasks,\n payload: payload,\n saturated: null,\n empty: null,\n drain: null,\n drained: true,\n push: function (data, callback) {\n if (!_isArray(data)) {\n data = [data];\n }\n _each(data, function(task) {\n tasks.push({\n data: task,\n callback: typeof callback === 'function' ? callback : null\n });\n cargo.drained = false;\n if (cargo.saturated && tasks.length === payload) {\n cargo.saturated();\n }\n });\n async.setImmediate(cargo.process);\n },\n process: function process() {\n if (working) return;\n if (tasks.length === 0) {\n if(cargo.drain && !cargo.drained) cargo.drain();\n cargo.drained = true;\n return;\n }\n\n var ts = typeof payload === 'number'\n ? tasks.splice(0, payload)\n : tasks.splice(0, tasks.length);\n\n var ds = _map(ts, function (task) {\n return task.data;\n });\n\n if(cargo.empty) cargo.empty();\n working = true;\n worker(ds, function () {\n working = false;\n\n var args = arguments;\n _each(ts, function (data) {\n if (data.callback) {\n data.callback.apply(null, args);\n }\n });\n\n process();\n });\n },\n length: function () {\n return tasks.length;\n },\n running: function () {\n return working;\n }\n };\n return cargo;\n };\n\n var _console_fn = function (name) {\n return function (fn) {\n var args = Array.prototype.slice.call(arguments, 1);\n fn.apply(null, args.concat([function (err) {\n var args = Array.prototype.slice.call(arguments, 1);\n if (typeof console !== 'undefined') {\n if (err) {\n if (console.error) {\n console.error(err);\n }\n }\n else if (console[name]) {\n _each(args, function (x) {\n console[name](x);\n });\n }\n }\n }]));\n };\n };\n async.log = _console_fn('log');\n async.dir = _console_fn('dir');\n /*async.info = _console_fn('info');\n async.warn = _console_fn('warn');\n async.error = _console_fn('error');*/\n\n async.memoize = function (fn, hasher) {\n var memo = {};\n var queues = {};\n hasher = hasher || function (x) {\n return x;\n };\n var memoized = function () {\n var args = Array.prototype.slice.call(arguments);\n var callback = args.pop();\n var key = hasher.apply(null, args);\n if (key in memo) {\n async.nextTick(function () {\n callback.apply(null, memo[key]);\n });\n }\n else if (key in queues) {\n queues[key].push(callback);\n }\n else {\n queues[key] = [callback];\n fn.apply(null, args.concat([function () {\n memo[key] = arguments;\n var q = queues[key];\n delete queues[key];\n for (var i = 0, l = q.length; i < l; i++) {\n q[i].apply(null, arguments);\n }\n }]));\n }\n };\n memoized.memo = memo;\n memoized.unmemoized = fn;\n return memoized;\n };\n\n async.unmemoize = function (fn) {\n return function () {\n return (fn.unmemoized || fn).apply(null, arguments);\n };\n };\n\n async.times = function (count, iterator, callback) {\n var counter = [];\n for (var i = 0; i < count; i++) {\n counter.push(i);\n }\n return async.map(counter, iterator, callback);\n };\n\n async.timesSeries = function (count, iterator, callback) {\n var counter = [];\n for (var i = 0; i < count; i++) {\n counter.push(i);\n }\n return async.mapSeries(counter, iterator, callback);\n };\n\n async.seq = function (/* functions... */) {\n var fns = arguments;\n return function () {\n var that = this;\n var args = Array.prototype.slice.call(arguments);\n var callback = args.pop();\n async.reduce(fns, args, function (newargs, fn, cb) {\n fn.apply(that, newargs.concat([function () {\n var err = arguments[0];\n var nextargs = Array.prototype.slice.call(arguments, 1);\n cb(err, nextargs);\n }]))\n },\n function (err, results) {\n callback.apply(that, [err].concat(results));\n });\n };\n };\n\n async.compose = function (/* functions... */) {\n return async.seq.apply(null, Array.prototype.reverse.call(arguments));\n };\n\n var _applyEach = function (eachfn, fns /*args...*/) {\n var go = function () {\n var that = this;\n var args = Array.prototype.slice.call(arguments);\n var callback = args.pop();\n return eachfn(fns, function (fn, cb) {\n fn.apply(that, args.concat([cb]));\n },\n callback);\n };\n if (arguments.length > 2) {\n var args = Array.prototype.slice.call(arguments, 2);\n return go.apply(this, args);\n }\n else {\n return go;\n }\n };\n async.applyEach = doParallel(_applyEach);\n async.applyEachSeries = doSeries(_applyEach);\n\n async.forever = function (fn, callback) {\n function next(err) {\n if (err) {\n if (callback) {\n return callback(err);\n }\n throw err;\n }\n fn(next);\n }\n next();\n };\n\n // Node.js\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = async;\n }\n // AMD / RequireJS\n else if (typeof define !== 'undefined' && define.amd) {\n define([], function () {\n return async;\n });\n }\n // included directly via