UNPKG

n3

Version:

Lightning fast, asynchronous, streaming Turtle / N3 / RDF library.

1 lines 280 kB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.N3=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _Util=require("./Util");const BASE_UNSUPPORTED=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i;const SUFFIX_SUPPORTED=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/;const CURRENT="./";const PARENT="../";const QUERY="?";const FRAGMENT="#";class BaseIRI{constructor(base){this.base=base;this._baseLength=0;this._baseMatcher=null;this._pathReplacements=new Array(base.length+1)}static supports(base){return!BASE_UNSUPPORTED.test(base)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const scheme=/^[^:]*:\/*/.exec(this.base)[0];const regexHead=["^",(0,_Util.escapeRegex)(scheme)];const regexTail=[];const segments=[],segmenter=/[^/?#]*([/?#])/y;let segment,query=0,fragment=0,last=segmenter.lastIndex=scheme.length;while(!query&&!fragment&&(segment=segmenter.exec(this.base))){if(segment[1]===FRAGMENT)fragment=segmenter.lastIndex-1;else{regexHead.push((0,_Util.escapeRegex)(segment[0]),"(?:");regexTail.push(")?");if(segment[1]!==QUERY)segments.push(last=segmenter.lastIndex);else{query=last=segmenter.lastIndex;fragment=this.base.indexOf(FRAGMENT,query);this._pathReplacements[query]=QUERY}}}for(let i=0;i<segments.length;i++)this._pathReplacements[segments[i]]=PARENT.repeat(segments.length-i-1);this._pathReplacements[segments[segments.length-1]]=CURRENT;this._baseLength=fragment>0?fragment:this.base.length;regexHead.push((0,_Util.escapeRegex)(this.base.substring(last,this._baseLength)),query?"(?:#|$)":"(?:[?#]|$)");return this._baseMatcher=new RegExp([...regexHead,...regexTail].join(""))}toRelative(iri){const match=this._getBaseMatcher().exec(iri);if(!match)return iri;const length=match[0].length;if(length===this._baseLength&&length===iri.length)return"";const parentPath=this._pathReplacements[length];if(parentPath){const suffix=iri.substring(length);if(parentPath!==QUERY&&!SUFFIX_SUPPORTED.test(suffix))return iri;if(parentPath===CURRENT&&/^[^?#]/.test(suffix))return suffix;return parentPath+suffix}return iri.substring(length-1)}}exports.default=BaseIRI},{"./Util":13}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/";var _default=exports.default={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`,dirLangString:`${RDF}dirLangString`,reifies:`${RDF}reifies`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}}},{}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.Variable=exports.Triple=exports.Term=exports.Quad=exports.NamedNode=exports.Literal=exports.DefaultGraph=exports.BlankNode=void 0;exports.escapeQuotes=escapeQuotes;exports.fromQuad=fromQuad;exports.fromTerm=fromTerm;exports.termFromId=termFromId;exports.termToId=termToId;exports.unescapeQuotes=unescapeQuotes;var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const{rdf,xsd}=_IRIs.default;let DEFAULTGRAPH;let _blankNodeCounter=0;const escapedLiteral=/^"(.*".*)(?="[^"]*$)/;const DataFactory={namedNode:namedNode,blankNode:blankNode,variable:variable,literal:literal,defaultGraph:defaultGraph,quad:quad,triple:quad,fromTerm:fromTerm,fromQuad:fromQuad};var _default=exports.default=DataFactory;class Term{constructor(id){this.id=id}get value(){return this.id}equals(other){if(other instanceof Term)return this.id===other.id;return!!other&&this.termType===other.termType&&this.value===other.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}exports.Term=Term;class NamedNode extends Term{get termType(){return"NamedNode"}}exports.NamedNode=NamedNode;class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const id=this.id;let atPos=id.lastIndexOf('"')+1;const dirPos=id.lastIndexOf("--");return atPos<id.length&&id[atPos++]==="@"?(dirPos>atPos?id.substr(0,dirPos):id).substr(atPos).toLowerCase():""}get direction(){const id=this.id;const endPos=id.lastIndexOf('"');const dirPos=id.lastIndexOf("--");return dirPos>endPos&&dirPos+2<id.length?id.substr(dirPos+2).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const id=this.id,dtPos=id.lastIndexOf('"')+1;const char=dtPos<id.length?id[dtPos]:"";return char==="^"?id.substr(dtPos+2):char!=="@"?xsd.string:id.indexOf("--",dtPos)>0?rdf.dirLangString:rdf.langString}equals(other){if(other instanceof Literal)return this.id===other.id;return!!other&&!!other.datatype&&this.termType===other.termType&&this.value===other.value&&this.language===other.language&&(this.direction===other.direction||this.direction===""&&!other.direction)&&this.datatype.value===other.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,direction:this.direction,datatype:{termType:"NamedNode",value:this.datatypeString}}}}exports.Literal=Literal;class BlankNode extends Term{constructor(name){super(`_:${name}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}exports.BlankNode=BlankNode;class Variable extends Term{constructor(name){super(`?${name}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}exports.Variable=Variable;class DefaultGraph extends Term{constructor(){super("");return DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(other){return this===other||!!other&&this.termType===other.termType}}exports.DefaultGraph=DefaultGraph;DEFAULTGRAPH=new DefaultGraph;function termFromId(id,factory,nested){factory=factory||DataFactory;if(!id)return factory.defaultGraph();switch(id[0]){case"?":return factory.variable(id.substr(1));case"_":return factory.blankNode(id.substr(2));case'"':if(factory===DataFactory)return new Literal(id);if(id[id.length-1]==='"')return factory.literal(id.substr(1,id.length-2));const endPos=id.lastIndexOf('"',id.length-1);let languageOrDatatype;if(id[endPos+1]==="@"){languageOrDatatype=id.substr(endPos+2);const dashDashIndex=languageOrDatatype.lastIndexOf("--");if(dashDashIndex>0&&dashDashIndex<languageOrDatatype.length){languageOrDatatype={language:languageOrDatatype.substr(0,dashDashIndex),direction:languageOrDatatype.substr(dashDashIndex+2)}}}else{languageOrDatatype=factory.namedNode(id.substr(endPos+3))}return factory.literal(id.substr(1,endPos-1),languageOrDatatype);case"[":id=JSON.parse(id);break;default:if(!nested||!Array.isArray(id)){return factory.namedNode(id)}}return factory.quad(termFromId(id[0],factory,true),termFromId(id[1],factory,true),termFromId(id[2],factory,true),id[3]&&termFromId(id[3],factory,true))}function termToId(term,nested){if(typeof term==="string")return term;if(term instanceof Term&&term.termType!=="Quad")return term.id;if(!term)return DEFAULTGRAPH.id;switch(term.termType){case"NamedNode":return term.value;case"BlankNode":return`_:${term.value}`;case"Variable":return`?${term.value}`;case"DefaultGraph":return"";case"Literal":return`"${term.value}"${term.language?`@${term.language}${term.direction?`--${term.direction}`:""}`:term.datatype&&term.datatype.value!==xsd.string?`^^${term.datatype.value}`:""}`;case"Quad":const res=[termToId(term.subject,true),termToId(term.predicate,true),termToId(term.object,true)];if(term.graph&&term.graph.termType!=="DefaultGraph"){res.push(termToId(term.graph,true))}return nested?res:JSON.stringify(res);default:throw new Error(`Unexpected termType: ${term.termType}`)}}class Quad extends Term{constructor(subject,predicate,object,graph){super("");this._subject=subject;this._predicate=predicate;this._object=object;this._graph=graph||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(other){return!!other&&this._subject.equals(other.subject)&&this._predicate.equals(other.predicate)&&this._object.equals(other.object)&&this._graph.equals(other.graph)}}exports.Triple=exports.Quad=Quad;function escapeQuotes(id){return id.replace(escapedLiteral,(_,quoted)=>`"${quoted.replace(/"/g,'""')}`)}function unescapeQuotes(id){return id.replace(escapedLiteral,(_,quoted)=>`"${quoted.replace(/""/g,'"')}`)}function namedNode(iri){return new NamedNode(iri)}function blankNode(name){return new BlankNode(name||`n3-${_blankNodeCounter++}`)}function literal(value,languageOrDataType){if(typeof languageOrDataType==="string")return new Literal(`"${value}"@${languageOrDataType.toLowerCase()}`);if(languageOrDataType!==undefined&&!("termType"in languageOrDataType)){return new Literal(`"${value}"@${languageOrDataType.language.toLowerCase()}${languageOrDataType.direction?`--${languageOrDataType.direction.toLowerCase()}`:""}`)}let datatype=languageOrDataType?languageOrDataType.value:"";if(datatype===""){if(typeof value==="boolean")datatype=xsd.boolean;else if(typeof value==="number"){if(Number.isFinite(value))datatype=Number.isInteger(value)?xsd.integer:xsd.double;else{datatype=xsd.double;if(!Number.isNaN(value))value=value>0?"INF":"-INF"}}}return datatype===""||datatype===xsd.string?new Literal(`"${value}"`):new Literal(`"${value}"^^${datatype}`)}function variable(name){return new Variable(name)}function defaultGraph(){return DEFAULTGRAPH}function quad(subject,predicate,object,graph){return new Quad(subject,predicate,object,graph)}function fromTerm(term){if(term instanceof Term)return term;switch(term.termType){case"NamedNode":return namedNode(term.value);case"BlankNode":return blankNode(term.value);case"Variable":return variable(term.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(term.value,term.language||term.datatype);case"Quad":return fromQuad(term);default:throw new Error(`Unexpected termType: ${term.termType}`)}}function fromQuad(inQuad){if(inQuad instanceof Quad)return inQuad;if(inQuad.termType!=="Quad")throw new Error(`Unexpected termType: ${inQuad.termType}`);return quad(fromTerm(inQuad.subject),fromTerm(inQuad.predicate),fromTerm(inQuad.object),fromTerm(inQuad.graph))}},{"./IRIs":2}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _buffer=require("buffer");var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const{xsd}=_IRIs.default;const escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g;const escapeReplacements={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"};const illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/;const lineModeRegExps={_iri:true,_unescapedIri:true,_simpleQuotedString:true,_langcode:true,_dircode:true,_blank:true,_newline:true,_comment:true,_whitespace:true,_endOfFile:true};const invalidRegExp=/$0^/;class N3Lexer{constructor(options){this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/;this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/;this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/;this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/;this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9])/i;this._dircode=/^--(ltr)|(rtl)/;this._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<])/;this._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}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/;this._variable=/^\?(?:(?:[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-: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])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/;this._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])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/;this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/;this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/;this._atKeyword=/^@[a-z]+(?=[\s#<:])/i;this._keyword=/^(?:PREFIX|BASE|VERSION|GRAPH)(?=[\s#<])/i;this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/;this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/;this._comment=/#([^\n\r]*)/;this._whitespace=/^[ \t]+/;this._endOfFile=/^(?:#[^\n\r]*)?$/;options=options||{};this._isImpliedBy=options.isImpliedBy;if(this._lineMode=!!options.lineMode){this._n3Mode=false;for(const key in this){if(!(key in lineModeRegExps)&&this[key]instanceof RegExp)this[key]=invalidRegExp}}else{this._n3Mode=options.n3!==false}this.comments=!!options.comments;this._literalClosingPos=0}_tokenizeToEnd(callback,inputFinished){let input=this._input;let currentLineLength=input.length;while(true){let whiteSpaceMatch,comment;while(whiteSpaceMatch=this._newline.exec(input)){if(this.comments&&(comment=this._comment.exec(whiteSpaceMatch[0])))emitToken("comment",comment[1],"",this._line,whiteSpaceMatch[0].length);input=input.substr(whiteSpaceMatch[0].length,input.length);currentLineLength=input.length;this._line++}if(!whiteSpaceMatch&&(whiteSpaceMatch=this._whitespace.exec(input)))input=input.substr(whiteSpaceMatch[0].length,input.length);if(this._endOfFile.test(input)){if(inputFinished){if(this.comments&&(comment=this._comment.exec(input)))emitToken("comment",comment[1],"",this._line,input.length);input=null;emitToken("eof","","",this._line,0)}return this._input=input}const line=this._line,firstChar=input[0];let type="",value="",prefix="",match=null,matchLength=0,inconclusive=false;switch(firstChar){case"^":if(input.length<3)break;else if(input[1]==="^"){this._previousMarker="^^";input=input.substr(2);if(input[0]!=="<"){inconclusive=true;break}}else{if(this._n3Mode){matchLength=1;type="^"}break}case"<":if(match=this._unescapedIri.exec(input))type="IRI",value=match[1];else if(match=this._iri.exec(input)){value=this._unescape(match[1]);if(value===null||illegalIriChars.test(value))return reportSyntaxError(this);type="IRI"}else if(input.length>2&&input[1]==="<"&&input[2]==="(")type="<<(",matchLength=3;else if(!this._lineMode&&input.length>(inputFinished?1:2)&&input[1]==="<")type="<<",matchLength=2;else if(this._n3Mode&&input.length>1&&input[1]==="="){matchLength=2;if(this._isImpliedBy)type="abbreviation",value="<";else type="inverse",value=">"}break;case">":if(input.length>1&&input[1]===">")type=">>",matchLength=2;break;case"_":if((match=this._blank.exec(input))||inputFinished&&(match=this._blank.exec(`${input} `)))type="blank",prefix="_",value=match[1];break;case'"':if(match=this._simpleQuotedString.exec(input))value=match[1];else{({value,matchLength}=this._parseLiteral(input));if(value===null)return reportSyntaxError(this)}if(match!==null||matchLength!==0){type="literal";this._literalClosingPos=0}break;case"'":if(!this._lineMode){if(match=this._simpleApostropheString.exec(input))value=match[1];else{({value,matchLength}=this._parseLiteral(input));if(value===null)return reportSyntaxError(this)}if(match!==null||matchLength!==0){type="literal";this._literalClosingPos=0}}break;case"?":if(this._n3Mode&&(match=this._variable.exec(input)))type="var",value=match[0];break;case"@":if(this._previousMarker==="literal"&&(match=this._langcode.exec(input))&&match[1]!=="version")type="langcode",value=match[1];else if(match=this._atKeyword.exec(input))type=match[0];break;case".":if(input.length===1?inputFinished:input[1]<"0"||input[1]>"9"){type=".";matchLength=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":if(input[1]==="-"){if(this._previousMarker==="langcode"&&(match=this._dircode.exec(input)))type="dircode",matchLength=2,value=match[1]||match[2],matchLength=value.length+2;break}if(match=this._number.exec(input)||inputFinished&&(match=this._number.exec(`${input} `))){type="literal",value=match[0];prefix=typeof match[1]==="string"?xsd.double:typeof match[2]==="string"?xsd.decimal:xsd.integer}break;case"B":case"b":case"p":case"P":case"G":case"g":case"V":case"v":if(match=this._keyword.exec(input))type=match[0].toUpperCase();else inconclusive=true;break;case"f":case"t":if(match=this._boolean.exec(input))type="literal",value=match[0],prefix=xsd.boolean;else inconclusive=true;break;case"a":if(match=this._shortPredicates.exec(input))type="abbreviation",value="a";else inconclusive=true;break;case"=":if(this._n3Mode&&input.length>1){type="abbreviation";if(input[1]!==">")matchLength=1,value="=";else matchLength=2,value=">"}break;case"!":if(!this._n3Mode)break;case")":if(!inputFinished&&(input.length===1||input.length===2&&input[1]===">")){break}if(input.length>2&&input[1]===">"&&input[2]===">"){type=")>>",matchLength=3;break}case",":case";":case"[":case"]":case"(":case"}":case"~":if(!this._lineMode){matchLength=1;type=firstChar}break;case"{":if(!this._lineMode&&input.length>=2){if(input[1]==="|")type="{|",matchLength=2;else type=firstChar,matchLength=1}break;case"|":if(input.length>=2&&input[1]==="}")type="|}",matchLength=2;break;default:inconclusive=true}if(inconclusive){if((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(match=this._prefix.exec(input)))type="prefix",value=match[1]||"";else if((match=this._prefixed.exec(input))||inputFinished&&(match=this._prefixed.exec(`${input} `)))type="prefixed",prefix=match[1]||"",value=this._unescape(match[2])}if(this._previousMarker==="^^"){switch(type){case"prefixed":type="type";break;case"IRI":type="typeIRI";break;default:type=""}}if(!type){if(inputFinished||!/^'''|^"""/.test(input)&&/\n|\r/.test(input))return reportSyntaxError(this);else return this._input=input}const length=matchLength||match[0].length;const token=emitToken(type,value,prefix,line,length);this.previousToken=token;this._previousMarker=type;input=input.substr(length,input.length)}function emitToken(type,value,prefix,line,length){const start=input?currentLineLength-input.length:currentLineLength;const end=start+length;const token={type:type,value:value,prefix:prefix,line:line,start:start,end:end};callback(null,token);return token}function reportSyntaxError(self){callback(self._syntaxError(/^\S*/.exec(input)[0]))}}_unescape(item){let invalid=false;const replaced=item.replace(escapeSequence,(sequence,unicode4,unicode8,escapedChar)=>{if(typeof unicode4==="string")return String.fromCharCode(Number.parseInt(unicode4,16));if(typeof unicode8==="string"){let charCode=Number.parseInt(unicode8,16);return charCode<=65535?String.fromCharCode(Number.parseInt(unicode8,16)):String.fromCharCode(55296+((charCode-=65536)>>10),56320+(charCode&1023))}if(escapedChar in escapeReplacements)return escapeReplacements[escapedChar];invalid=true;return""});return invalid?null:replaced}_parseLiteral(input){if(input.length>=3){const opening=input.match(/^(?:"""|"|'''|'|)/)[0];const openingLength=opening.length;let closingPos=Math.max(this._literalClosingPos,openingLength);while((closingPos=input.indexOf(opening,closingPos))>0){let backslashCount=0;while(input[closingPos-backslashCount-1]==="\\")backslashCount++;if(backslashCount%2===0){const raw=input.substring(openingLength,closingPos);const lines=raw.split(/\r\n|\r|\n/).length-1;const matchLength=closingPos+openingLength;if(openingLength===1&&lines!==0||openingLength===3&&this._lineMode)break;this._line+=lines;return{value:this._unescape(raw),matchLength:matchLength}}closingPos++}this._literalClosingPos=input.length-openingLength+1}return{value:"",matchLength:0}}_syntaxError(issue){this._input=null;const err=new Error(`Unexpected "${issue}" on line ${this._line}.`);err.context={token:undefined,line:this._line,previousToken:this.previousToken};return err}_readStartingBom(input){return input.startsWith("\ufeff")?input.substr(1):input}tokenize(input,callback){this._line=1;if(typeof input==="string"){this._input=this._readStartingBom(input);if(typeof callback==="function")queueMicrotask(()=>this._tokenizeToEnd(callback,true));else{const tokens=[];let error;this._tokenizeToEnd((e,t)=>e?error=e:tokens.push(t),true);if(error)throw error;return tokens}}else{this._pendingBuffer=null;if(typeof input.setEncoding==="function")input.setEncoding("utf8");input.on("data",data=>{if(this._input!==null&&data.length!==0){if(this._pendingBuffer){data=_buffer.Buffer.concat([this._pendingBuffer,data]);this._pendingBuffer=null}if(data[data.length-1]&128){this._pendingBuffer=data}else{if(typeof this._input==="undefined")this._input=this._readStartingBom(typeof data==="string"?data:data.toString());else this._input+=data;this._tokenizeToEnd(callback,false)}}});input.on("end",()=>{if(typeof this._input==="string")this._tokenizeToEnd(callback,true)});input.on("error",callback)}}}exports.default=N3Lexer},{"./IRIs":2,buffer:17}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _N3Lexer=_interopRequireDefault(require("./N3Lexer"));var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}let blankNodePrefix=0;class N3Parser{constructor(options){this._contextStack=[];this._graph=null;options=options||{};this._setBase(options.baseIRI);options.factory&&initDataFactory(this,options.factory);const format=typeof options.format==="string"?options.format.match(/\w*$/)[0].toLowerCase():"",isTurtle=/turtle/.test(format),isTriG=/trig/.test(format),isNTriples=/triple/.test(format),isNQuads=/quad/.test(format),isN3=this._n3Mode=/n3/.test(format),isLineMode=isNTriples||isNQuads;if(!(this._supportsNamedGraphs=!(isTurtle||isN3)))this._readPredicateOrNamedGraph=this._readPredicate;this._supportsQuads=!(isTurtle||isTriG||isNTriples||isN3);this._isImpliedBy=options.isImpliedBy;if(isLineMode)this._resolveRelativeIRI=iri=>{return null};this._blankNodePrefix=typeof options.blankNodePrefix!=="string"?"":options.blankNodePrefix.replace(/^(?!_:)/,"_:");this._lexer=options.lexer||new _N3Lexer.default({lineMode:isLineMode,n3:isN3,isImpliedBy:this._isImpliedBy});this._explicitQuantifiers=!!options.explicitQuantifiers;this._parseUnsupportedVersions=!!options.parseUnsupportedVersions;this._version=options.version}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(baseIRI){if(!baseIRI){this._base="";this._basePath=""}else{const fragmentPos=baseIRI.indexOf("#");if(fragmentPos>=0)baseIRI=baseIRI.substr(0,fragmentPos);this._base=baseIRI;this._basePath=baseIRI.indexOf("/")<0?baseIRI:baseIRI.replace(/[^\/?]*(?:\?.*)?$/,"");baseIRI=baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i);this._baseRoot=baseIRI[0];this._baseScheme=baseIRI[1]}}_saveContext(type,graph,subject,predicate,object){const n3Mode=this._n3Mode;this._contextStack.push({type:type,subject:subject,predicate:predicate,object:object,graph:graph,inverse:n3Mode?this._inversePredicate:false,blankPrefix:n3Mode?this._prefixes._:"",quantified:n3Mode?this._quantified:null});if(n3Mode){this._inversePredicate=false;this._prefixes._=this._graph?`${this._graph.value}.`:".";this._quantified=Object.create(this._quantified)}}_restoreContext(type,token){const context=this._contextStack.pop();if(!context||context.type!==type)return this._error(`Unexpected ${token.type}`,token);this._subject=context.subject;this._predicate=context.predicate;this._object=context.object;this._graph=context.graph;if(this._n3Mode){this._inversePredicate=context.inverse;this._prefixes._=context.blankPrefix;this._quantified=context.quantified}}_readBeforeTopContext(token){if(this._version&&!this._isValidVersion(this._version))return this._error(`Detected unsupported version as media type parameter: "${this._version}"`,token);return this._readInTopContext(token)}_readInTopContext(token){switch(token.type){case"eof":if(this._graph!==null)return this._error("Unclosed graph",token);delete this._prefixes._;return this._callback(null,null,this._prefixes);case"PREFIX":this._sparqlStyle=true;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=true;case"@base":return this._readBaseIRI;case"VERSION":this._sparqlStyle=true;case"@version":return this._readVersion;case"{":if(this._supportsNamedGraphs){this._graph="";this._subject=null;return this._readSubject}case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(token)}}_readEntity(token,quantifier){let value;switch(token.type){case"IRI":case"typeIRI":const iri=this._resolveIRI(token.value);if(iri===null)return this._error("Invalid IRI",token);value=this._factory.namedNode(iri);break;case"type":case"prefixed":const prefix=this._prefixes[token.prefix];if(prefix===undefined)return this._error(`Undefined prefix "${token.prefix}:"`,token);value=this._factory.namedNode(prefix+token.value);break;case"blank":value=this._factory.blankNode(this._prefixes[token.prefix]+token.value);break;case"var":value=this._factory.variable(token.value.substr(1));break;default:return this._error(`Expected entity but got ${token.type}`,token)}if(!quantifier&&this._n3Mode&&value.id in this._quantified)value=this._quantified[value.id];return value}_readSubject(token){this._predicate=null;switch(token.type){case"[":this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null);return this._readBlankNodeHead;case"(":const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];if(parent.type==="<<"){return this._error("Unexpected list in reified triple",token)}this._saveContext("list",this._graph,this.RDF_NIL,null,null);this._subject=null;return this._readListItem;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null);return this._readSubject;case"}":return this._readPunctuation(token);case"@forSome":if(!this._n3Mode)return this._error('Unexpected "@forSome"',token);this._subject=null;this._predicate=this.N3_FORSOME;this._quantifier="blankNode";return this._readQuantifierList;case"@forAll":if(!this._n3Mode)return this._error('Unexpected "@forAll"',token);this._subject=null;this._predicate=this.N3_FORALL;this._quantifier="variable";return this._readQuantifierList;case"literal":if(!this._n3Mode)return this._error("Unexpected literal",token);if(token.prefix.length===0){this._literalValue=token.value;return this._completeSubjectLiteral}else this._subject=this._factory.literal(token.value,this._factory.namedNode(token.prefix));break;case"<<(":if(!this._n3Mode)return this._error("Disallowed triple term as subject",token);this._saveContext("<<(",this._graph,null,null,null);this._graph=null;return this._readSubject;case"<<":this._saveContext("<<",this._graph,null,null,null);this._graph=null;return this._readSubject;default:if((this._subject=this._readEntity(token))===undefined)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(token){const type=token.type;switch(type){case"inverse":this._inversePredicate=true;case"abbreviation":this._predicate=this.ABBREVIATIONS[token.value];break;case".":case"]":case"}":case"|}":if(this._predicate===null)return this._error(`Unexpected ${type}`,token);this._subject=null;return type==="]"?this._readBlankNodeTail(token):this._readPunctuation(token);case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",token);case"[":if(this._n3Mode){this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null);return this._readBlankNodeHead}case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",token);default:if((this._predicate=this._readEntity(token))===undefined)return}this._validAnnotation=true;return this._readObject}_readObject(token){switch(token.type){case"literal":if(token.prefix.length===0){this._literalValue=token.value;return this._readDataTypeOrLang}else this._object=this._factory.literal(token.value,this._factory.namedNode(token.prefix));break;case"[":this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode());return this._readBlankNodeHead;case"(":const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];if(parent.type==="<<"){return this._error("Unexpected list in reified triple",token)}this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL);this._subject=null;return this._readListItem;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode());return this._readSubject;case"<<(":this._saveContext("<<(",this._graph,this._subject,this._predicate,null);this._graph=null;return this._readSubject;case"<<":this._saveContext("<<",this._graph,this._subject,this._predicate,null);this._graph=null;return this._readSubject;default:if((this._object=this._readEntity(token))===undefined)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(token){return token.type==="{"?this._readGraph(token):this._readPredicate(token)}_readGraph(token){if(token.type!=="{")return this._error(`Expected graph but got ${token.type}`,token);this._graph=this._subject,this._subject=null;return this._readSubject}_readBlankNodeHead(token){if(token.type==="]"){this._subject=null;return this._readBlankNodeTail(token)}else{const stack=this._contextStack,parentParent=stack.length>1&&stack[stack.length-2];if(parentParent.type==="<<"){return this._error("Unexpected compound blank node expression in reified triple",token)}this._predicate=null;return this._readPredicate(token)}}_readBlankNodeTail(token){if(token.type!=="]")return this._readBlankNodePunctuation(token);if(this._subject!==null)this._emit(this._subject,this._predicate,this._object,this._graph);const empty=this._predicate===null;this._restoreContext("blank",token);if(this._object!==null)return this._getContextEndReader();else if(this._predicate!==null)return this._readObject;else return empty?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(token){switch(token.type){case".":case"}":this._subject=null;return this._readPunctuation(token);default:return this._readPredicate(token)}}_readListItem(token){let item=null,list=null,next=this._readListItem;const previousList=this._subject,stack=this._contextStack,parent=stack[stack.length-1];switch(token.type){case"[":this._saveContext("blank",this._graph,list=this._factory.blankNode(),this.RDF_FIRST,this._subject=item=this._factory.blankNode());next=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,list=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL);this._subject=null;break;case")":this._restoreContext("list",token);if(stack.length!==0&&stack[stack.length-1].type==="list")this._emit(this._subject,this._predicate,this._object,this._graph);if(this._predicate===null){next=this._readPredicate;if(this._subject===this.RDF_NIL)return next}else{next=this._getContextEndReader();if(this._object===this.RDF_NIL)return next}list=this.RDF_NIL;break;case"literal":if(token.prefix.length===0){this._literalValue=token.value;next=this._readListItemDataTypeOrLang}else{item=this._factory.literal(token.value,this._factory.namedNode(token.prefix));next=this._getContextEndReader()}break;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode());return this._readSubject;case"<<":this._saveContext("<<",this._graph,null,null,null);this._graph=null;next=this._readSubject;break;default:if((item=this._readEntity(token))===undefined)return}if(list===null)this._subject=list=this._factory.blankNode();if(token.type==="<<")stack[stack.length-1].subject=this._subject;if(previousList===null){if(parent.predicate===null)parent.subject=list;else parent.object=list}else{this._emit(previousList,this.RDF_REST,list,this._graph)}if(item!==null){if(this._n3Mode&&(token.type==="IRI"||token.type==="prefixed")){this._saveContext("item",this._graph,list,this.RDF_FIRST,item);this._subject=item,this._predicate=null;return this._getPathReader(this._readListItem)}this._emit(list,this.RDF_FIRST,item,this._graph)}return next}_readDataTypeOrLang(token){return this._completeObjectLiteral(token,false)}_readListItemDataTypeOrLang(token){return this._completeObjectLiteral(token,true)}_completeLiteral(token,component){let literal=this._factory.literal(this._literalValue);let readCb;switch(token.type){case"type":case"typeIRI":const datatype=this._readEntity(token);if(datatype===undefined)return;if(datatype.value===_IRIs.default.rdf.langString||datatype.value===_IRIs.default.rdf.dirLangString){return this._error("Detected illegal (directional) languaged-tagged string with explicit datatype",token)}literal=this._factory.literal(this._literalValue,datatype);token=null;break;case"langcode":if(token.value.split("-").some(t=>t.length>8))return this._error("Detected language tag with subtag longer than 8 characters",token);literal=this._factory.literal(this._literalValue,token.value);this._literalLanguage=token.value;token=null;readCb=this._readDirCode.bind(this,component);break}return{token:token,literal:literal,readCb:readCb}}_readDirCode(component,listItem,token){if(token.type==="dircode"){const term=this._factory.literal(this._literalValue,{language:this._literalLanguage,direction:token.value});if(component==="subject")this._subject=term;else this._object=term;this._literalLanguage=undefined;token=null}if(component==="subject")return token===null?this._readPredicateOrNamedGraph:this._readPredicateOrNamedGraph(token);return this._completeObjectLiteralPost(token,listItem)}_completeSubjectLiteral(token){const completed=this._completeLiteral(token,"subject");this._subject=completed.literal;if(completed.readCb)return completed.readCb.bind(this,false);return this._readPredicateOrNamedGraph}_completeObjectLiteral(token,listItem){const completed=this._completeLiteral(token,"object");if(!completed)return;this._object=completed.literal;if(completed.readCb)return completed.readCb.bind(this,listItem);return this._completeObjectLiteralPost(completed.token,listItem)}_completeObjectLiteralPost(token,listItem){if(listItem)this._emit(this._subject,this.RDF_FIRST,this._object,this._graph);if(token===null)return this._getContextEndReader();else{this._readCallback=this._getContextEndReader();return this._readCallback(token)}}_readFormulaTail(token){if(token.type!=="}")return this._readPunctuation(token);if(this._subject!==null)this._emit(this._subject,this._predicate,this._object,this._graph);this._restoreContext("formula",token);return this._object===null?this._readPredicate:this._getContextEndReader()}_readPunctuation(token){let next,graph=this._graph,startingAnnotation=false;const subject=this._subject,inversePredicate=this._inversePredicate;switch(token.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",token);if(this._n3Mode)return this._readFormulaTail(token);this._graph=null;case".":this._subject=null;this._tripleTerm=null;next=this._contextStack.length?this._readSubject:this._readInTopContext;if(inversePredicate)this._inversePredicate=false;break;case";":next=this._readPredicate;break;case",":next=this._readObject;break;case"~":next=this._readReifierInAnnotation;startingAnnotation=true;break;case"{|":this._subject=this._readTripleTerm();this._validAnnotation=false;startingAnnotation=true;next=this._readPredicate;break;case"|}":if(!this._annotation)return this._error("Unexpected annotation syntax closing",token);if(!this._validAnnotation)return this._error("Annotation block can not be empty",token);this._subject=null;this._annotation=false;next=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(graph=this._readEntity(token))!==undefined){next=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,token)}if(subject!==null&&(!startingAnnotation||startingAnnotation&&!this._annotation)){const predicate=this._predicate,object=this._object;if(!inversePredicate)this._emit(subject,predicate,object,graph);else this._emit(object,predicate,subject,graph)}if(startingAnnotation){this._annotation=true}return next}_readBlankNodePunctuation(token){let next;switch(token.type){case";":next=this._readPredicate;break;case",":next=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,token)}this._emit(this._subject,this._predicate,this._object,this._graph);return next}_readQuadPunctuation(token){if(token.type!==".")return this._error("Expected dot to follow quad",token);return this._readInTopContext}_readPrefix(token){if(token.type!=="prefix")return this._error("Expected prefix to follow @prefix",token);this._prefix=token.value;return this._readPrefixIRI}_readPrefixIRI(token){if(token.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,token);const prefixNode=this._readEntity(token);this._prefixes[this._prefix]=prefixNode.value;this._prefixCallback(this._prefix,prefixNode);return this._readDeclarationPunctuation}_readBaseIRI(token){const iri=token.type==="IRI"&&this._resolveIRI(token.value);if(!iri)return this._error("Expected valid IRI to follow base declaration",token);this._setBase(iri);return this._readDeclarationPunctuation}_isValidVersion(version){return this._parseUnsupportedVersions||N3Parser.SUPPORTED_VERSIONS.includes(version)}_readVersion(token){if(token.type!=="literal")return this._error("Expected literal to follow version declaration",token);if(token.end-token.start!==token.value.length+2)return this._error("Version declarations must use single quotes",token);this._versionCallback(token.value);if(!this._isValidVersion(token.value))return this._error(`Detected unsupported version: "${token.value}"`,token);return this._readDeclarationPunctuation}_readNamedGraphLabel(token){switch(token.type){case"IRI":case"blank":case"prefixed":return this._readSubject(token),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",token)}}_readNamedGraphBlankLabel(token){if(token.type!=="]")return this._error("Invalid graph label",token);this._subject=this._factory.blankNode();return this._readGraph}_readDeclarationPunctuation(token){if(this._sparqlStyle){this._sparqlStyle=false;return this._readInTopContext(token)}if(token.type!==".")return this._error("Expected declaration to end with a dot",token);return this._readInTopContext}_readQuantifierList(token){let entity;switch(token.type){case"IRI":case"prefixed":if((entity=this._readEntity(token,true))!==undefined)break;default:return this._error(`Unexpected ${token.type}`,token)}if(!this._explicitQuantifiers)this._quantified[entity.id]=this._factory[this._quantifier](this._factory.blankNode().value);else{if(this._subject===null)this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH);else this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH);this._emit(this._subject,this.RDF_FIRST,entity,this.QUANTIFIERS_GRAPH)}return this._readQuantifierPunctuation}_readQuantifierPunctuation(token){if(token.type===",")return this._readQuantifierList;else{if(this._explicitQuantifiers){this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH);this._subject=null}this._readCallback=this._getContextEndReader();return this._readCallback(token)}}_getPathReader(afterPath){this._afterPath=afterPath;return this._readPath}_readPath(token){switch(token.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];if(parent&&parent.type==="item"){const item=this._subject;this._restoreContext("item",token);this._emit(this._subject,this.RDF_FIRST,item,this._graph)}return this._afterPath(token)}}_readForwardPath(token){let subject,predicate;const object=this._factory.blankNode();if((predicate=this._readEntity(token))===undefined)return;if(this._predicate===null)subject=this._subject,this._subject=object;else subject=this._object,this._object=object;this._emit(subject,predicate,object,this._graph);return this._readPath}_readBackwardPath(token){const subject=this._factory.blankNode();let predicate,object;if((predicate=this._readEntity(token))===undefined)return;if(this._predicate===null)object=this._subject,this._subject=subject;else object=this._object,this._object=subject;this._emit(subject,predicate,object,this._graph);return this._readPath}_readTripleTermTail(token){if(token.type!==")>>")return this._error(`Expected )>> but got ${token.type}`,token);const quad=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);this._restoreContext("<<(",token);if(this._subject===null){this._subject=quad;return this._readPredicate}else{this._object=quad;return this._getContextEndReader()}}_readReifiedTripleTailOrReifier(token){if(token.type==="~"){return this._readReifier}return this._readReifiedTripleTail(token)}_readReifiedTripleTail(token){if(token.type!==">>")return this._error(`Expected >> but got ${token.type}`,token);this._tripleTerm=null;const reifier=this._readTripleTerm();this._restoreContext("<<",token);const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];if(parent&&parent.type==="list"){this._emit(this._subject,this.RDF_FIRST,reifier,this._graph);return this._getContextEndReader()}else if(this._subject===null){this._subject=reifier;return this._readPredicateOrReifierTripleEnd}else{this._object=reifier;return this._getContextEndReader()}}_readPredicateOrReifierTripleEnd(token){if(token.type==="."){this._subject=null;return this._readPunctuation(token)}return this._readPredicate(token)}_readReifier(token){this._reifier=this._readEntity(token);return this._readReifiedTripleTail}_readReifierInAnnotation(token){if(token.type==="IRI"||token.type==="typeIRI"||token.type==="type"||token.type==="prefixed"||token.type==="blank"||token.type==="var"){this._reifier=this._readEntity(token);return this._readPunctuation}this._readTripleTerm();this._subject=null;return this._readPunctuation(token)}_readTripleTerm(){const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];const parentGraph=parent?parent.graph:undefined;const reifier=this._reifier||this._factory.blankNode();this._reifier=null;this._tripleTerm=this._tripleTerm||this._factory.quad(this._subject,this._predicate,this._object);this._emit(reifier,this.RDF_REIFIES,this._tripleTerm,parentGraph||this.DEFAULTGRAPH);return reifier}_getContextEndReader(){const contextStack=this._contextStack;if(!contextStack.length)return this._readPunctuation;switch(contextStack[contextStack.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<(":return this._readTripleTermTail;case"<<":return this._readReifiedTripleTailOrReifier}}_emit(subject,predicate,object,graph){this._callback(null,this._factory.quad(subject,predicate,object,graph||this.DEFAULTGRAPH))}_error(message,token){const err=new Error(`${message} on line ${token.line}.`);err.context={token:token,line:token.line,previousToken:this._lexer.previousToken};this._callback(err);this._callback=noop}_resolveIRI(iri){return/^[a-z][a-z0-9+.-]*:/i.test(iri)?iri:this._resolveRelativeIRI(iri)}_resolveRelativeIRI(iri){if(!iri.length)return this._base;switch(iri[0]){case"#":return this._base+iri;case"?":return this._base.replace(/(?:\?.*)?$/,iri);case"/":return(iri[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(iri);default:return/^[^/:]*:/.test(iri)?null:this._removeDotSegments(this._basePath+iri)}}_removeDotSegments(iri){if(!/(^|\/)\.\.?($|[/#?])/.test(iri))return iri;const length=iri.length;let result="",i=-1,pathStart=-1,segmentStart=0,next="/";while(i<length){switch(next){case":":if(pathStart<0){if(iri[++i]==="/"&&iri[++i]==="/")while((pathStart=i+1)<length&&iri[pathStart]!=="/")i=pathStart}break;case"?":case"#":i=length;break;case"/":if(iri[i+1]==="."){next=iri[++i+1];switch(next){case"/":result+=iri.substring(segmentStart,i-1);segmentStart=i+1;break;case undefined:case"?":case"#":return result+iri.substring(segmentStart,i)+iri.substr(i+1);case".":next=iri[++i+1];if(next===undefined||next==="/"||next==="?"||next==="#"){result+=iri.substring(segmentStart,i-2);if((segmentStart=result.lastIndexOf("/"))>=pathStart)result=result.substr(0,segmentStart);if(next!=="/")return`${result}/${iri.substr(i+1)}`;segmentStart=i+1}}}}next=iri[++i]}return result+iri.substring(segmentStart)}parse(input,quadCallback,prefixCallback,versionCallback){let onQuad,onPrefix,onComment,onVersion;if(quadCallback&&(quadCallback.onQuad||quadCallback.onPrefix||quadCallback.onComment||quadCallback.onVersion)){onQuad=quadCallback.onQuad;onPrefix=quadCallback.onPrefix;onComment=quadCallback.onComment;onVersion=quadCallback.onVersion}else{onQuad=quadCallback;onPrefix=prefixCallback;onVersion=versionCallback}this._readCallback=this._readBeforeTopContext;this._sparqlStyle=false;this._prefixes=Object.create(null);this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`;this._prefixCallback=onPrefix||noop;this._versionCallback=onVersion||noop;this._inversePredicate=false;this._quantified=Object.create(null);if(!onQuad){const quads=[];let error;this._callback=(e,t)=>{e?error=e:t&&quads.push(t)};this._lexer.tokenize(input).every(token=>{return this._readCallback=this._readCallback(token)});if(error)throw error;return quads}let processNextToken=(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback)this._readCallback=this._readCallback(token)};if(onComment){this._lexer.comments=true;processNextToken=(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback){if(token.type==="comment")onComment(token.value);else this._readCallback=this._readCallback(token)}}}this._callback=onQuad;this._lexer.tokenize(input,processNextToken)}}exports.default=N3Parser;function noop(){}function initDataFactory(parser,factory){parser._factory=factory;parser.DEFAULTGRAPH=factory.defaultGraph();parser.RDF_FIRST=factory.namedNode(_IRIs.default.rdf.first);parser.RDF_REST=factory.namedNode(_IRIs.default.rdf.rest);parser.RDF_NIL=factory.namedNode(_IRIs.default.rdf.nil);parser.RDF_REIFIES=factory.namedNode(_IRIs