(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`"${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()}`);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)}},{"./IRIs":1}],3:[function(require,module,exports){(function(Buffer){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _queueMicrotask=_interopRequireDefault(require("queue-microtask"));var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}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,_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._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._keyword=/^@[a-z]+(?=[\s#<:])/i;this._sparqlKeyword=/^(?:PREFIX|BASE|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||{};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>1&&input[1]==="<")type="<<",matchLength=2;else if(this._n3Mode&&input.length>1&&input[1]==="=")type="inverse",matchLength=2,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)))type="langcode",value=match[1];else if(match=this._keyword.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(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":if(match=this._sparqlKeyword.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",":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")(0,_queueMicrotask.default)(()=>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.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}).call(this)}).call(this,require("buffer").Buffer)},{"./IRIs":1,buffer:15,"queue-microtask":19}],4:[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(obj){return obj&&obj.__esModule?obj:{default:obj}}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._supportsRDFStar=format===""||/star|\*$/.test(format);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});this._explicitQuantifiers=!!options.explicitQuantifiers}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}}_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"{":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._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._namedNode(prefix+token.value);break;case"blank":value=this._blankNode(this._prefixes[token.prefix]+token.value);break;case"var":value=this._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._blankNode(),null,null);return this._readBlankNodeHead;case"(":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._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=this._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=this._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._literal(token.value,this._namedNode(token.prefix));break;case"<<":if(!this._supportsRDFStar)return this._error("Unexpected RDF* syntax",token);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"}":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._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}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._literal(token.value,this._namedNode(token.prefix));break;case"[":this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._blankNode());return this._readBlankNodeHead;case"(":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._blankNode());return this._readSubject;case"<<":if(!this._supportsRDFStar)return this._error("Unexpected RDF* syntax",token);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{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._blankNode(),this.RDF_FIRST,this._subject=item=this._blankNode());next=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,list=this._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._literal(token.value,this._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._blankNode());return this._readSubject;default:if((item=this._readEntity(token))===undefined)return}if(list===null)this._subject=list=this._blankNode();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){let literal=this._literal(this._literalValue);switch(token.type){case"type":case"typeIRI":const datatype=this._readEntity(token);if(datatype===undefined)return;literal=this._literal(this._literalValue,datatype);token=null;break;case"langcode":literal=this._literal(this._literalValue,token.value);token=null;break}return{token:token,literal:literal}}_completeSubjectLiteral(token){this._subject=this._completeLiteral(token).literal;return this._readPredicateOrNamedGraph}_completeObjectLiteral(token,listItem){const completed=this._completeLiteral(token);if(!completed)return;this._object=completed.literal;if(listItem)this._emit(this._subject,this.RDF_FIRST,this._object,this._graph);if(completed.token===null)return this._getContextEndReader();else{this._readCallback=this._getContextEndReader();return this._readCallback(completed.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;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;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"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF* syntax",token);const predicate=this._predicate,object=this._object;this._subject=this._quad(subject,predicate,object,this.DEFAULTGRAPH);next=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",token);this._subject=null;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){const predicate=this._predicate,object=this._object;if(!inversePredicate)this._emit(subject,predicate,object,graph);else this._emit(object,predicate,subject,graph)}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}_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._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._quantifier(this._blankNode().value);else{if(this._subject===null)this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._blankNode(),this.QUANTIFIERS_GRAPH);else this._emit(this._subject,this.RDF_REST,this._subject=this._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._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._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}_readRDFStarTailOrGraph(token){if(token.type!==">>"){if(this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(token))!==undefined)return this._readRDFStarTail;return this._error(`Expected >> to follow "${this._object.id}"`,token)}return this._readRDFStarTail(token)}_readRDFStarTail(token){if(token.type!==">>")return this._error(`Expected >> but got ${token.type}`,token);const quad=this._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()}}_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._readRDFStarTailOrGraph}}_emit(subject,predicate,object,graph){this._callback(null,this._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=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){this._readCallback=this._readInTopContext;this._sparqlStyle=false;this._prefixes=Object.create(null);this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`;this._prefixCallback=prefixCallback||noop;this._inversePredicate=false;this._quantified=Object.create(null);if(!quadCallback){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}this._callback=quadCallback;this._lexer.tokenize(input,(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback)this._readCallback=this._readCallback(token)})}}exports.default=N3Parser;function noop(){}function initDataFactory(parser,factory){const namedNode=factory.namedNode;parser._namedNode=namedNode;parser._blankNode=factory.blankNode;parser._literal=factory.literal;parser._variable=factory.variable;parser._quad=factory.quad;parser.DEFAULTGRAPH=factory.defaultGraph();parser.RDF_FIRST=namedNode(_IRIs.default.rdf.first);parser.RDF_REST=namedNode(_IRIs.default.rdf.rest);parser.RDF_NIL=namedNode(_IRIs.default.rdf.nil);parser.N3_FORALL=namedNode(_IRIs.default.r.forAll);parser.N3_FORSOME=namedNode(_IRIs.default.r.forSome);parser.ABBREVIATIONS={a:namedNode(_IRIs.default.rdf.type),"=":namedNode(_IRIs.default.owl.sameAs),">":namedNode(_IRIs.default.log.implies)};parser.QUANTIFIERS_GRAPH=namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,_N3DataFactory.default)},{"./IRIs":1,"./N3DataFactory":2,"./N3Lexer":3}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _readableStream=require("readable-stream");var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));var _IRIs=_interopRequireDefault(require("./IRIs"));var _N3Util=require("./N3Util");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}class N3Store{constructor(quads,options){this._size=0;this._graphs=Object.create(null);this._id=0;this._ids=Object.create(null);this._entities=Object.create(null);this._blankNodeIndex=0;if(!options&&quads&&!quads[0])options=quads,quads=null;options=options||{};this._factory=options.factory||_N3DataFactory.default;if(quads)this.addQuads(quads)}_termFromId(id,factory){if(id[0]==="."){const entities=this._entities;const terms=id.split(".");const q=this._factory.quad(this._termFromId(entities[terms[1]]),this._termFromId(entities[terms[2]]),this._termFromId(entities[terms[3]]),terms[4]&&this._termFromId(entities[terms[4]]));return q}return(0,_N3DataFactory.termFromId)(id,factory)}_termToNumericId(term){if(term.termType==="Quad"){const s=this._termToNumericId(term.subject),p=this._termToNumericId(term.predicate),o=this._termToNumericId(term.object);let g;return s&&p&&o&&((0,_N3Util.isDefaultGraph)(term.graph)||(g=this._termToNumericId(term.graph)))&&this._ids[g?`.${s}.${p}.${o}.${g}`:`.${s}.${p}.${o}`]}return this._ids[(0,_N3DataFactory.termToId)(term)]}_termToNewNumericId(term){const str=term&&term.termType==="Quad"?`.${this._termToNewNumericId(term.subject)}.${this._termToNewNumericId(term.predicate)}.${this._termToNewNumericId(term.object)}${(0,_N3Util.isDefaultGraph)(term.graph)?"":`.${this._termToNewNumericId(term.graph)}`}`:(0,_N3DataFactory.termToId)(term);return this._ids[str]||(this._ids[this._entities[++this._id]=str]=this._id)}get size(){let size=this._size;if(size!==null)return size;size=0;const graphs=this._graphs;let subjects,subject;for(const graphKey in graphs)for(const subjectKey in subjects=graphs[graphKey].subjects)for(const predicateKey in subject=subjects[subjectKey])size+=Object.keys(subject[predicateKey]).length;return this._size=size}_addToIndex(index0,key0,key1,key2){const index1=index0[key0]||(index0[key0]={});const index2=index1[key1]||(index1[key1]={});const existed=key2 in index2;if(!existed)index2[key2]=null;return!existed}_removeFromIndex(index0,key0,key1,key2){const index1=index0[key0],index2=index1[key1];delete index2[key2];for(const key in index2)return;delete index1[key1];for(const key in index1)return;delete index0[key0]}*_findInIndex(index0,key0,key1,key2,name0,name1,name2,graphId){let tmp,index1,index2;const entityKeys=this._entities;const graph=this._termFromId(graphId,this._factory);const parts={subject:null,predicate:null,object:null};if(key0)(tmp=index0,index0={})[key0]=tmp[key0];for(const value0 in index0){if(index1=index0[value0]){parts[name0]=this._termFromId(entityKeys[value0],this._factory);if(key1)(tmp=index1,index1={})[key1]=tmp[key1];for(const value1 in index1){if(index2=index1[value1]){parts[name1]=this._termFromId(entityKeys[value1],this._factory);const values=key2?key2 in index2?[key2]:[]:Object.keys(index2);for(let l=0;l{if(!(id in uniqueIds)){uniqueIds[id]=true;callback(this._termFromId(this._entities[id],this._factory))}}}add(quad){this.addQuad(quad);return this}addQuad(subject,predicate,object,graph){if(!predicate)graph=subject.graph,object=subject.object,predicate=subject.predicate,subject=subject.subject;graph=(0,_N3DataFactory.termToId)(graph);let graphItem=this._graphs[graph];if(!graphItem){graphItem=this._graphs[graph]={subjects:{},predicates:{},objects:{}};Object.freeze(graphItem)}subject=this._termToNewNumericId(subject);predicate=this._termToNewNumericId(predicate);object=this._termToNewNumericId(object);const changed=this._addToIndex(graphItem.subjects,subject,predicate,object);this._addToIndex(graphItem.predicates,predicate,object,subject);this._addToIndex(graphItem.objects,object,subject,predicate);this._size=null;return changed}addQuads(quads){for(let i=0;i{this.addQuad(quad)});return stream}removeQuad(subject,predicate,object,graph){if(!predicate)graph=subject.graph,object=subject.object,predicate=subject.predicate,subject=subject.subject;graph=(0,_N3DataFactory.termToId)(graph);const graphs=this._graphs;let graphItem,subjects,predicates;if(!(subject=subject&&this._termToNumericId(subject))||!(predicate=predicate&&this._termToNumericId(predicate))||!(object=object&&this._termToNumericId(object))||!(graphItem=graphs[graph])||!(subjects=graphItem.subjects[subject])||!(predicates=subjects[predicate])||!(object in predicates))return false;this._removeFromIndex(graphItem.subjects,subject,predicate,object);this._removeFromIndex(graphItem.predicates,predicate,object,subject);this._removeFromIndex(graphItem.objects,object,subject,predicate);if(this._size!==null)this._size--;for(subject in graphItem.subjects)return true;delete graphs[graph];return true}removeQuads(quads){for(let i=0;i{this.removeQuad(quad)});return stream}removeMatches(subject,predicate,object,graph){const stream=new _readableStream.Readable({objectMode:true});stream._read=()=>{for(const quad of this.readQuads(subject,predicate,object,graph))stream.push(quad);stream.push(null)};return this.remove(stream)}deleteGraph(graph){return this.removeMatches(null,null,null,graph)}getQuads(subject,predicate,object,graph){return[...this.readQuads(subject,predicate,object,graph)]}*readQuads(subject,predicate,object,graph){graph=graph&&(0,_N3DataFactory.termToId)(graph);const graphs=this._getGraphs(graph);let content,subjectId,predicateId,objectId;if(subject&&!(subjectId=this._termToNumericId(subject))||predicate&&!(predicateId=this._termToNumericId(predicate))||object&&!(objectId=this._termToNumericId(object)))return;for(const graphId in graphs){if(content=graphs[graphId]){if(subjectId){if(objectId)yield*this._findInIndex(content.objects,objectId,subjectId,predicateId,"object","subject","predicate",graphId);else yield*this._findInIndex(content.subjects,subjectId,predicateId,null,"subject","predicate","object",graphId)}else if(predicateId)yield*this._findInIndex(content.predicates,predicateId,objectId,null,"predicate","object","subject",graphId);else if(objectId)yield*this._findInIndex(content.objects,objectId,null,null,"object","subject","predicate",graphId);else yield*this._findInIndex(content.subjects,null,null,null,"subject","predicate","object",graphId)}}}match(subject,predicate,object,graph){return new DatasetCoreAndReadableStream(this,subject,predicate,object,graph)}countQuads(subject,predicate,object,graph){graph=graph&&(0,_N3DataFactory.termToId)(graph);const graphs=this._getGraphs(graph);let count=0,content,subjectId,predicateId,objectId;if(subject&&!(subjectId=this._termToNumericId(subject))||predicate&&!(predicateId=this._termToNumericId(predicate))||object&&!(objectId=this._termToNumericId(object)))return 0;for(const graphId in graphs){if(content=graphs[graphId]){if(subject){if(object)count+=this._countInIndex(content.objects,objectId,subjectId,predicateId);else count+=this._countInIndex(content.subjects,subjectId,predicateId,objectId)}else if(predicate){count+=this._countInIndex(content.predicates,predicateId,objectId,subjectId)}else{count+=this._countInIndex(content.objects,objectId,subjectId,predicateId)}}}return count}forEach(callback,subject,predicate,object,graph){this.some(quad=>{callback(quad);return false},subject,predicate,object,graph)}every(callback,subject,predicate,object,graph){let some=false;const every=!this.some(quad=>{some=true;return!callback(quad)},subject,predicate,object,graph);return some&&every}some(callback,subject,predicate,object,graph){for(const quad of this.readQuads(subject,predicate,object,graph))if(callback(quad))return true;return false}getSubjects(predicate,object,graph){const results=[];this.forSubjects(s=>{results.push(s)},predicate,object,graph);return results}forSubjects(callback,predicate,object,graph){graph=graph&&(0,_N3DataFactory.termToId)(graph);const graphs=this._getGraphs(graph);let content,predicateId,objectId;callback=this._uniqueEntities(callback);if(predicate&&!(predicateId=this._termToNumericId(predicate))||object&&!(objectId=this._termToNumericId(object)))return;for(graph in graphs){if(content=graphs[graph]){if(predicateId){if(objectId)this._loopBy2Keys(content.predicates,predicateId,objectId,callback);else this._loopByKey1(content.subjects,predicateId,callback)}else if(objectId)this._loopByKey0(content.objects,objectId,callback);else this._loop(content.subjects,callback)}}}getPredicates(subject,object,graph){const results=[];this.forPredicates(p=>{results.push(p)},subject,object,graph);return results}forPredicates(callback,subject,object,graph){graph=graph&&(0,_N3DataFactory.termToId)(graph);const graphs=this._getGraphs(graph);let content,subjectId,objectId;callback=this._uniqueEntities(callback);if(subject&&!(subjectId=this._termToNumericId(subject))||object&&!(objectId=this._termToNumericId(object)))return;for(graph in graphs){if(content=graphs[graph]){if(subjectId){if(objectId)this._loopBy2Keys(content.objects,objectId,subjectId,callback);else this._loopByKey0(content.subjects,subjectId,callback)}else if(objectId)this._loopByKey1(content.predicates,objectId,callback);else this._loop(content.predicates,callback)}}}getObjects(subject,predicate,graph){const results=[];this.forObjects(o=>{results.push(o)},subject,predicate,graph);return results}forObjects(callback,subject,predicate,graph){graph=graph&&(0,_N3DataFactory.termToId)(graph);const graphs=this._getGraphs(graph);let content,subjectId,predicateId;callback=this._uniqueEntities(callback);if(subject&&!(subjectId=this._termToNumericId(subject))||predicate&&!(predicateId=this._termToNumericId(predicate)))return;for(graph in graphs){if(content=graphs[graph]){if(subjectId){if(predicateId)this._loopBy2Keys(content.subjects,subjectId,predicateId,callback);else this._loopByKey1(content.objects,subjectId,callback)}else if(predicateId)this._loopByKey0(content.predicates,predicateId,callback);else this._loop(content.objects,callback)}}}getGraphs(subject,predicate,object){const results=[];this.forGraphs(g=>{results.push(g)},subject,predicate,object);return results}forGraphs(callback,subject,predicate,object){for(const graph in this._graphs){this.some(quad=>{callback(quad.graph);return true},subject,predicate,object,graph)}}createBlankNode(suggestedName){let name,index;if(suggestedName){name=suggestedName=`_:${suggestedName}`,index=1;while(this._ids[name])name=suggestedName+index++}else{do{name=`_:b${this._blankNodeIndex++}`}while(this._ids[name])}this._ids[name]=++this._id;this._entities[this._id]=name;return this._factory.blankNode(name.substr(2))}extractLists({remove=false,ignoreErrors=false}={}){const lists={};const onError=ignoreErrors?()=>true:(node,message)=>{throw new Error(`${node.value} ${message}`)};const tails=this.getQuads(null,_IRIs.default.rdf.rest,_IRIs.default.rdf.nil,null);const toRemove=remove?[...tails]:[];tails.forEach(tailQuad=>{const items=[];let malformed=false;let head;let headPos;const graph=tailQuad.graph;let current=tailQuad.subject;while(current&&!malformed){const objectQuads=this.getQuads(null,null,current,null);const subjectQuads=this.getQuads(current,null,null,null);let quad,first=null,rest=null,parent=null;for(let i=0;i{switch(event){case"data":onData=callback;break;case"end":onEnd=callback;break}}},(error,quad)=>{error&&this.emit("error",error)||quad&&this.push(quad)},(prefix,uri)=>{this.emit("prefix",prefix,uri)});this._transform=(chunk,encoding,done)=>{onData(chunk);done()};this._flush=done=>{onEnd();done()}}import(stream){stream.on("data",chunk=>{this.write(chunk)});stream.on("end",()=>{this.end()});stream.on("error",error=>{this.emit("error",error)});return this}}exports.default=N3StreamParser},{"./N3Parser":4,"readable-stream":38}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _readableStream=require("readable-stream");var _N3Writer=_interopRequireDefault(require("./N3Writer"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}class N3StreamWriter extends _readableStream.Transform{constructor(options){super({encoding:"utf8",writableObjectMode:true});const writer=this._writer=new _N3Writer.default({write:(quad,encoding,callback)=>{this.push(quad);callback&&callback()},end:callback=>{this.push(null);callback&&callback()}},options);this._transform=(quad,encoding,done)=>{writer.addQuad(quad,done)};this._flush=done=>{writer.end(done)}}import(stream){stream.on("data",quad=>{this.write(quad)});stream.on("end",()=>{this.end()});stream.on("error",error=>{this.emit("error",error)});stream.on("prefix",(prefix,iri)=>{this._writer.addPrefix(prefix,iri)});return this}}exports.default=N3StreamWriter},{"./N3Writer":9,"readable-stream":38}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.inDefaultGraph=inDefaultGraph;exports.isBlankNode=isBlankNode;exports.isDefaultGraph=isDefaultGraph;exports.isLiteral=isLiteral;exports.isNamedNode=isNamedNode;exports.isVariable=isVariable;exports.prefix=prefix;exports.prefixes=prefixes;var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function isNamedNode(term){return!!term&&term.termType==="NamedNode"}function isBlankNode(term){return!!term&&term.termType==="BlankNode"}function isLiteral(term){return!!term&&term.termType==="Literal"}function isVariable(term){return!!term&&term.termType==="Variable"}function isDefaultGraph(term){return!!term&&term.termType==="DefaultGraph"}function inDefaultGraph(quad){return isDefaultGraph(quad.graph)}function prefix(iri,factory){return prefixes({"":iri.value||iri},factory)("")}function prefixes(defaultPrefixes,factory){const prefixes=Object.create(null);for(const prefix in defaultPrefixes)processPrefix(prefix,defaultPrefixes[prefix]);factory=factory||_N3DataFactory.default;function processPrefix(prefix,iri){if(typeof iri==="string"){const cache=Object.create(null);prefixes[prefix]=local=>{return cache[local]||(cache[local]=factory.namedNode(iri+local))}}else if(!(prefix in prefixes)){throw new Error(`Unknown prefix: ${prefix}`)}return prefixes[prefix]}return processPrefix}},{"./N3DataFactory":2}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _IRIs=_interopRequireDefault(require("./IRIs"));var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));var _N3Util=require("./N3Util");function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const DEFAULTGRAPH=_N3DataFactory.default.defaultGraph();const{rdf,xsd}=_IRIs.default;const escape=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,escapeAll=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,escapedCharacters={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class SerializedTerm extends _N3DataFactory.Term{equals(other){return other===this}}class N3Writer{constructor(outputStream,options){this._prefixRegex=/$0^/;if(outputStream&&typeof outputStream.write!=="function")options=outputStream,outputStream=null;options=options||{};this._lists=options.lists;if(!outputStream){let output="";this._outputStream={write(chunk,encoding,done){output+=chunk;done&&done()},end:done=>{done&&done(null,output)}};this._endStream=true}else{this._outputStream=outputStream;this._endStream=options.end===undefined?true:!!options.end}this._subject=null;if(!/triple|quad/i.test(options.format)){this._lineMode=false;this._graph=DEFAULTGRAPH;this._prefixIRIs=Object.create(null);options.prefixes&&this.addPrefixes(options.prefixes);if(options.baseIRI){this._baseMatcher=new RegExp(`^${escapeRegex(options.baseIRI)}${options.baseIRI.endsWith("/")?"":"[#?]"}`);this._baseLength=options.baseIRI.length}}else{this._lineMode=true;this._writeQuad=this._writeQuadLine}}get _inDefaultGraph(){return DEFAULTGRAPH.equals(this._graph)}_write(string,callback){this._outputStream.write(string,"utf8",callback)}_writeQuad(subject,predicate,object,graph,done){try{if(!graph.equals(this._graph)){this._write((this._subject===null?"":this._inDefaultGraph?".\n":"\n}\n")+(DEFAULTGRAPH.equals(graph)?"":`${this._encodeIriOrBlank(graph)} {\n`));this._graph=graph;this._subject=null}if(subject.equals(this._subject)){if(predicate.equals(this._predicate))this._write(`, ${this._encodeObject(object)}`,done);else this._write(`;\n ${this._encodePredicate(this._predicate=predicate)} ${this._encodeObject(object)}`,done)}else this._write(`${(this._subject===null?"":".\n")+this._encodeSubject(this._subject=subject)} ${this._encodePredicate(this._predicate=predicate)} ${this._encodeObject(object)}`,done)}catch(error){done&&done(error)}}_writeQuadLine(subject,predicate,object,graph,done){delete this._prefixMatch;this._write(this.quadToString(subject,predicate,object,graph),done)}quadToString(subject,predicate,object,graph){return`${this._encodeSubject(subject)} ${this._encodeIriOrBlank(predicate)} ${this._encodeObject(object)}${graph&&graph.value?` ${this._encodeIriOrBlank(graph)} .\n`:" .\n"}`}quadsToString(quads){return quads.map(t=>{return this.quadToString(t.subject,t.predicate,t.object,t.graph)}).join("")}_encodeSubject(entity){return entity.termType==="Quad"?this._encodeQuad(entity):this._encodeIriOrBlank(entity)}_encodeIriOrBlank(entity){if(entity.termType!=="NamedNode"){if(this._lists&&entity.value in this._lists)entity=this.list(this._lists[entity.value]);return"id"in entity?entity.id:`_:${entity.value}`}let iri=entity.value;if(this._baseMatcher&&this._baseMatcher.test(iri))iri=iri.substr(this._baseLength);if(escape.test(iri))iri=iri.replace(escapeAll,characterReplacer);const prefixMatch=this._prefixRegex.exec(iri);return!prefixMatch?`<${iri}>`:!prefixMatch[1]?iri:this._prefixIRIs[prefixMatch[1]]+prefixMatch[2]}_encodeLiteral(literal){let value=literal.value;if(escape.test(value))value=value.replace(escapeAll,characterReplacer);if(literal.language)return`"${value}"@${literal.language}`;if(this._lineMode){if(literal.datatype.value===xsd.string)return`"${value}"`}else{switch(literal.datatype.value){case xsd.string:return`"${value}"`;case xsd.boolean:if(value==="true"||value==="false")return value;break;case xsd.integer:if(/^[+-]?\d+$/.test(value))return value;break;case xsd.decimal:if(/^[+-]?\d*\.\d+$/.test(value))return value;break;case xsd.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(value))return value;break}}return`"${value}"^^${this._encodeIriOrBlank(literal.datatype)}`}_encodePredicate(predicate){return predicate.value===rdf.type?"a":this._encodeIriOrBlank(predicate)}_encodeObject(object){switch(object.termType){case"Quad":return this._encodeQuad(object);case"Literal":return this._encodeLiteral(object);default:return this._encodeIriOrBlank(object)}}_encodeQuad({subject,predicate,object,graph}){return`<<${this._encodeSubject(subject)} ${this._encodePredicate(predicate)} ${this._encodeObject(object)}${(0,_N3Util.isDefaultGraph)(graph)?"":` ${this._encodeIriOrBlank(graph)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(subject,predicate,object,graph,done){if(object===undefined)this._writeQuad(subject.subject,subject.predicate,subject.object,subject.graph,predicate);else if(typeof graph==="function")this._writeQuad(subject,predicate,object,DEFAULTGRAPH,graph);else this._writeQuad(subject,predicate,object,graph||DEFAULTGRAPH,done)}addQuads(quads){for(let i=0;i.\n`)}if(hasPrefixes){let IRIlist="",prefixList="";for(const prefixIRI in this._prefixIRIs){IRIlist+=IRIlist?`|${prefixIRI}`:prefixIRI;prefixList+=(prefixList?"|":"")+this._prefixIRIs[prefixIRI]}IRIlist=escapeRegex(IRIlist,/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&");this._prefixRegex=new RegExp(`^(?:${prefixList})[^\/]*$|`+`^(${IRIlist})([_a-zA-Z][\\-_a-zA-Z0-9]*)$`)}this._write(hasPrefixes?"\n":"",done)}blank(predicate,object){let children=predicate,child,length;if(predicate===undefined)children=[];else if(predicate.termType)children=[{predicate:predicate,object:object}];else if(!("length"in predicate))children=[predicate];switch(length=children.length){case 0:return new SerializedTerm("[]");case 1:child=children[0];if(!(child.object instanceof SerializedTerm))return new SerializedTerm(`[ ${this._encodePredicate(child.predicate)} ${this._encodeObject(child.object)} ]`);default:let contents="[";for(let i=0;i{singleDone=null,done(error,result)});if(this._endStream){try{return this._outputStream.end(singleDone)}catch(error){}}singleDone&&singleDone()}}exports.default=N3Writer;function characterReplacer(character){let result=escapedCharacters[character];if(result===undefined){if(character.length===1){result=character.charCodeAt(0).toString(16);result="\\u0000".substr(0,6-result.length)+result}else{result=((character.charCodeAt(0)-55296)*1024+character.charCodeAt(1)+9216).toString(16);result="\\U00000000".substr(0,10-result.length)+result}}return result}function escapeRegex(regex){return regex.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}},{"./IRIs":1,"./N3DataFactory":2,"./N3Util":8}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"BlankNode",{enumerable:true,get:function(){return _N3DataFactory.BlankNode}});Object.defineProperty(exports,"DataFactory",{enumerable:true,get:function(){return _N3DataFactory.default}});Object.defineProperty(exports,"DefaultGraph",{enumerable:true,get:function(){return _N3DataFactory.DefaultGraph}});Object.defineProperty(exports,"Lexer",{enumerable:true,get:function(){return _N3Lexer.default}});Object.defineProperty(exports,"Literal",{enumerable:true,get:function(){return _N3DataFactory.Literal}});Object.defineProperty(exports,"NamedNode",{enumerable:true,get:function(){return _N3DataFactory.NamedNode}});Object.defineProperty(exports,"Parser",{enumerable:true,get:function(){return _N3Parser.default}});Object.defineProperty(exports,"Quad",{enumerable:true,get:function(){return _N3DataFactory.Quad}});Object.defineProperty(exports,"Store",{enumerable:true,get:function(){return _N3Store.default}});Object.defineProperty(exports,"StreamParser",{enumerable:true,get:function(){return _N3StreamParser.default}});Object.defineProperty(exports,"StreamWriter",{enumerable:true,get:function(){return _N3StreamWriter.default}});Object.defineProperty(exports,"Term",{enumerable:true,get:function(){return _N3DataFactory.Term}});Object.defineProperty(exports,"Triple",{enumerable:true,get:function(){return _N3DataFactory.Triple}});exports.Util=void 0;Object.defineProperty(exports,"Variable",{enumerable:true,get:function(){return _N3DataFactory.Variable}});Object.defineProperty(exports,"Writer",{enumerable:true,get:function(){return _N3Writer.default}});exports.default=void 0;Object.defineProperty(exports,"termFromId",{enumerable:true,get:function(){return _N3DataFactory.termFromId}});Object.defineProperty(exports,"termToId",{enumerable:true,get:function(){return _N3DataFactory.termToId}});var _N3Lexer=_interopRequireDefault(require("./N3Lexer"));var _N3Parser=_interopRequireDefault(require("./N3Parser"));var _N3Writer=_interopRequireDefault(require("./N3Writer"));var _N3Store=_interopRequireDefault(require("./N3Store"));var _N3StreamParser=_interopRequireDefault(require("./N3StreamParser"));var _N3StreamWriter=_interopRequireDefault(require("./N3StreamWriter"));var Util=_interopRequireWildcard(require("./N3Util"));exports.Util=Util;var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default=exports.default={Lexer:_N3Lexer.default,Parser:_N3Parser.default,Writer:_N3Writer.default,Store:_N3Store.default,StreamParser:_N3StreamParser.default,StreamWriter:_N3StreamWriter.default,Util:Util,DataFactory:_N3DataFactory.default,Term:_N3DataFactory.Term,NamedNode:_N3DataFactory.NamedNode,Literal:_N3DataFactory.Literal,BlankNode:_N3DataFactory.BlankNode,Variable:_N3DataFactory.Variable,DefaultGraph:_N3DataFactory.DefaultGraph,Quad:_N3DataFactory.Quad,Triple:_N3DataFactory.Triple,termFromId:_N3DataFactory.termFromId,termToId:_N3DataFactory.termToId}},{"./N3DataFactory":2,"./N3Lexer":3,"./N3Parser":4,"./N3Store":5,"./N3StreamParser":6,"./N3StreamWriter":7,"./N3Util":8,"./N3Writer":9}],11:[function(require,module,exports){"use strict";const{AbortController,AbortSignal}=typeof self!=="undefined"?self:typeof window!=="undefined"?window:undefined;module.exports=AbortController;module.exports.AbortSignal=AbortSignal;module.exports.default=AbortController},{}],12:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],13:[function(require,module,exports){var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:15}],14:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var isEncoding=Buffer.isEncoding||function(encoding){encoding=""+encoding;switch(encoding&&encoding.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 true;default:return false}};function _normalizeEncoding(enc){if(!enc)return"utf8";var retried;while(true){switch(enc){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 enc;default:if(retried)return;enc=(""+enc).toLowerCase();retried=true}}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if(typeof nenc!=="string"&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}exports.StringDecoder=StringDecoder;function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;nb=4;break;case"utf8":this.fillLast=utf8FillLast;nb=4;break;case"base64":this.text=base64Text;this.end=base64End;nb=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=Buffer.allocUnsafe(nb)}StringDecoder.prototype.write=function(buf){if(buf.length===0)return"";var r;var i;if(this.lastNeed){r=this.fillLast(buf);if(r===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return byte>>6===2?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j=0){if(nb>0){if(nb===2)nb=0;else self.lastNeed=nb-3}return nb}return 0}function utf8CheckExtraBytes(self,buf,p){if((buf[0]&192)!==128){self.lastNeed=0;return"�"}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�"}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�"}}}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,buf,p);if(r!==undefined)return r;if(this.lastNeed<=buf.length){buf.copy(this.lastChar,p,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,p,0,buf.length);this.lastNeed-=buf.length}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);buf.copy(this.lastChar,0,end);return buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+"�";return r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=buf[buf.length-1];return buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;if(n===0)return buf.toString("base64",i);this.lastNeed=3-n;this.lastTotal=3;if(n===1){this.lastChar[0]=buf[buf.length-1]}else{this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1]}return buf.toString("base64",i,buf.length-n)}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}},{"safe-buffer":13}],15:[function(require,module,exports){(function(Buffer){(function(){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;imax)str+=" ... ";return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":12,buffer:15,ieee754:17}],16:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],18:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i(promise||(promise=Promise.resolve())).then(cb).catch(err=>setTimeout(()=>{throw err},0))}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],20:[function(require,module,exports){"use strict";const{AbortError,codes}=require("../../ours/errors");const{isNodeStream,isWebStream,kControllerErrorFunction}=require("./utils");const eos=require("./end-of-stream");const{ERR_INVALID_ARG_TYPE}=codes;const validateAbortSignal=(signal,name)=>{if(typeof signal!=="object"||!("aborted"in signal)){throw new ERR_INVALID_ARG_TYPE(name,"AbortSignal",signal)}};module.exports.addAbortSignal=function addAbortSignal(signal,stream){validateAbortSignal(signal,"signal");if(!isNodeStream(stream)&&!isWebStream(stream)){throw new ERR_INVALID_ARG_TYPE("stream",["ReadableStream","WritableStream","Stream"],stream)}return module.exports.addAbortSignalNoValidate(signal,stream)};module.exports.addAbortSignalNoValidate=function(signal,stream){if(typeof signal!=="object"||!("aborted"in signal)){return stream}const onAbort=isNodeStream(stream)?()=>{stream.destroy(new AbortError(undefined,{cause:signal.reason}))}:()=>{stream[kControllerErrorFunction](new AbortError(undefined,{cause:signal.reason}))};if(signal.aborted){onAbort()}else{signal.addEventListener("abort",onAbort);eos(stream,()=>signal.removeEventListener("abort",onAbort))}return stream}},{"../../ours/errors":39,"./end-of-stream":26,"./utils":35}],21:[function(require,module,exports){"use strict";const{StringPrototypeSlice,SymbolIterator,TypedArrayPrototypeSet,Uint8Array}=require("../../ours/primordials");const{Buffer}=require("buffer");const{inspect}=require("../../ours/util");module.exports=class BufferList{constructor(){this.head=null;this.tail=null;this.length=0}push(v){const entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length}unshift(v){const entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length}shift(){if(this.length===0)return;const ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret}clear(){this.head=this.tail=null;this.length=0}join(s){if(this.length===0)return"";let p=this.head;let ret=""+p.data;while((p=p.next)!==null)ret+=s+p.data;return ret}concat(n){if(this.length===0)return Buffer.alloc(0);const ret=Buffer.allocUnsafe(n>>>0);let p=this.head;let i=0;while(p){TypedArrayPrototypeSet(ret,p.data,i);i+=p.data.length;p=p.next}return ret}consume(n,hasStrings){const data=this.head.data;if(nstr.length){ret+=str;n-=str.length}else{if(n===str.length){ret+=str;++c;if(p.next)this.head=p.next;else this.head=this.tail=null}else{ret+=StringPrototypeSlice(str,0,n);this.head=p;p.data=StringPrototypeSlice(str,n)}break}++c}while((p=p.next)!==null);this.length-=c;return ret}_getBuffer(n){const ret=Buffer.allocUnsafe(n);const retLen=n;let p=this.head;let c=0;do{const buf=p.data;if(n>buf.length){TypedArrayPrototypeSet(ret,buf,retLen-n);n-=buf.length}else{if(n===buf.length){TypedArrayPrototypeSet(ret,buf,retLen-n);++c;if(p.next)this.head=p.next;else this.head=this.tail=null}else{TypedArrayPrototypeSet(ret,new Uint8Array(buf.buffer,buf.byteOffset,n),retLen-n);this.head=p;p.data=buf.slice(n)}break}++c}while((p=p.next)!==null);this.length-=c;return ret}[Symbol.for("nodejs.util.inspect.custom")](_,options){return inspect(this,{...options,depth:0,customInspect:false})}}},{"../../ours/primordials":40,"../../ours/util":41,buffer:15}],22:[function(require,module,exports){"use strict";const{pipeline}=require("./pipeline");const Duplex=require("./duplex");const{destroyer}=require("./destroy");const{isNodeStream,isReadable,isWritable,isWebStream,isTransformStream,isWritableStream,isReadableStream}=require("./utils");const{AbortError,codes:{ERR_INVALID_ARG_VALUE,ERR_MISSING_ARGS}}=require("../../ours/errors");const eos=require("./end-of-stream");module.exports=function compose(...streams){if(streams.length===0){throw new ERR_MISSING_ARGS("streams")}if(streams.length===1){return Duplex.from(streams[0])}const orgStreams=[...streams];if(typeof streams[0]==="function"){streams[0]=Duplex.from(streams[0])}if(typeof streams[streams.length-1]==="function"){const idx=streams.length-1;streams[idx]=Duplex.from(streams[idx])}for(let n=0;n0&&!(isWritable(streams[n])||isWritableStream(streams[n])||isTransformStream(streams[n]))){throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`,orgStreams[n],"must be writable")}}let ondrain;let onfinish;let onreadable;let onclose;let d;function onfinished(err){const cb=onclose;onclose=null;if(cb){cb(err)}else if(err){d.destroy(err)}else if(!readable&&!writable){d.destroy()}}const head=streams[0];const tail=pipeline(streams,onfinished);const writable=!!(isWritable(head)||isWritableStream(head)||isTransformStream(head));const readable=!!(isReadable(tail)||isReadableStream(tail)||isTransformStream(tail));d=new Duplex({writableObjectMode:!!(head!==null&&head!==undefined&&head.writableObjectMode),readableObjectMode:!!(tail!==null&&tail!==undefined&&tail.writableObjectMode),writable:writable,readable:readable});if(writable){if(isNodeStream(head)){d._write=function(chunk,encoding,callback){if(head.write(chunk,encoding)){callback()}else{ondrain=callback}};d._final=function(callback){head.end();onfinish=callback};head.on("drain",function(){if(ondrain){const cb=ondrain;ondrain=null;cb()}})}else if(isWebStream(head)){const writable=isTransformStream(head)?head.writable:head;const writer=writable.getWriter();d._write=async function(chunk,encoding,callback){try{await writer.ready;writer.write(chunk).catch(()=>{});callback()}catch(err){callback(err)}};d._final=async function(callback){try{await writer.ready;writer.close().catch(()=>{});onfinish=callback}catch(err){callback(err)}}}const toRead=isTransformStream(tail)?tail.readable:tail;eos(toRead,()=>{if(onfinish){const cb=onfinish;onfinish=null;cb()}})}if(readable){if(isNodeStream(tail)){tail.on("readable",function(){if(onreadable){const cb=onreadable;onreadable=null;cb()}});tail.on("end",function(){d.push(null)});d._read=function(){while(true){const buf=tail.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf)){return}}}}else if(isWebStream(tail)){const readable=isTransformStream(tail)?tail.readable:tail;const reader=readable.getReader();d._read=async function(){while(true){try{const{value,done}=await reader.read();if(!d.push(value)){return}if(done){d.push(null);return}}catch{return}}}}}d._destroy=function(err,callback){if(!err&&onclose!==null){err=new AbortError}onreadable=null;ondrain=null;onfinish=null;if(onclose===null){callback(err)}else{onclose=callback;if(isNodeStream(tail)){destroyer(tail,err)}}};return d}},{"../../ours/errors":39,"./destroy":23,"./duplex":24,"./end-of-stream":26,"./pipeline":31,"./utils":35}],23:[function(require,module,exports){"use strict";const process=require("process/");const{aggregateTwoErrors,codes:{ERR_MULTIPLE_CALLBACK},AbortError}=require("../../ours/errors");const{Symbol}=require("../../ours/primordials");const{kDestroyed,isDestroyed,isFinished,isServerRequest}=require("./utils");const kDestroy=Symbol("kDestroy");const kConstruct=Symbol("kConstruct");function checkError(err,w,r){if(err){err.stack;if(w&&!w.errored){w.errored=err}if(r&&!r.errored){r.errored=err}}}function destroy(err,cb){const r=this._readableState;const w=this._writableState;const s=w||r;if(w!==null&&w!==undefined&&w.destroyed||r!==null&&r!==undefined&&r.destroyed){if(typeof cb==="function"){cb()}return this}checkError(err,w,r);if(w){w.destroyed=true}if(r){r.destroyed=true}if(!s.constructed){this.once(kDestroy,function(er){_destroy(this,aggregateTwoErrors(er,err),cb)})}else{_destroy(this,err,cb)}return this}function _destroy(self,err,cb){let called=false;function onDestroy(err){if(called){return}called=true;const r=self._readableState;const w=self._writableState;checkError(err,w,r);if(w){w.closed=true}if(r){r.closed=true}if(typeof cb==="function"){cb(err)}if(err){process.nextTick(emitErrorCloseNT,self,err)}else{process.nextTick(emitCloseNT,self)}}try{self._destroy(err||null,onDestroy)}catch(err){onDestroy(err)}}function emitErrorCloseNT(self,err){emitErrorNT(self,err);emitCloseNT(self)}function emitCloseNT(self){const r=self._readableState;const w=self._writableState;if(w){w.closeEmitted=true}if(r){r.closeEmitted=true}if(w!==null&&w!==undefined&&w.emitClose||r!==null&&r!==undefined&&r.emitClose){self.emit("close")}}function emitErrorNT(self,err){const r=self._readableState;const w=self._writableState;if(w!==null&&w!==undefined&&w.errorEmitted||r!==null&&r!==undefined&&r.errorEmitted){return}if(w){w.errorEmitted=true}if(r){r.errorEmitted=true}self.emit("error",err)}function undestroy(){const r=this._readableState;const w=this._writableState;if(r){r.constructed=true;r.closed=false;r.closeEmitted=false;r.destroyed=false;r.errored=null;r.errorEmitted=false;r.reading=false;r.ended=r.readable===false;r.endEmitted=r.readable===false}if(w){w.constructed=true;w.destroyed=false;w.closed=false;w.closeEmitted=false;w.errored=null;w.errorEmitted=false;w.finalCalled=false;w.prefinished=false;w.ended=w.writable===false;w.ending=w.writable===false;w.finished=w.writable===false}}function errorOrDestroy(stream,err,sync){const r=stream._readableState;const w=stream._writableState;if(w!==null&&w!==undefined&&w.destroyed||r!==null&&r!==undefined&&r.destroyed){return this}if(r!==null&&r!==undefined&&r.autoDestroy||w!==null&&w!==undefined&&w.autoDestroy)stream.destroy(err);else if(err){err.stack;if(w&&!w.errored){w.errored=err}if(r&&!r.errored){r.errored=err}if(sync){process.nextTick(emitErrorNT,stream,err)}else{emitErrorNT(stream,err)}}}function construct(stream,cb){if(typeof stream._construct!=="function"){return}const r=stream._readableState;const w=stream._writableState;if(r){r.constructed=false}if(w){w.constructed=false}stream.once(kConstruct,cb);if(stream.listenerCount(kConstruct)>1){return}process.nextTick(constructNT,stream)}function constructNT(stream){let called=false;function onConstruct(err){if(called){errorOrDestroy(stream,err!==null&&err!==undefined?err:new ERR_MULTIPLE_CALLBACK);return}called=true;const r=stream._readableState;const w=stream._writableState;const s=w||r;if(r){r.constructed=true}if(w){w.constructed=true}if(s.destroyed){stream.emit(kDestroy,err)}else if(err){errorOrDestroy(stream,err,true)}else{process.nextTick(emitConstructNT,stream)}}try{stream._construct(err=>{process.nextTick(onConstruct,err)})}catch(err){process.nextTick(onConstruct,err)}}function emitConstructNT(stream){stream.emit(kConstruct)}function isRequest(stream){return(stream===null||stream===undefined?undefined:stream.setHeader)&&typeof stream.abort==="function"}function emitCloseLegacy(stream){stream.emit("close")}function emitErrorCloseLegacy(stream,err){stream.emit("error",err);process.nextTick(emitCloseLegacy,stream)}function destroyer(stream,err){if(!stream||isDestroyed(stream)){return}if(!err&&!isFinished(stream)){err=new AbortError}if(isServerRequest(stream)){stream.socket=null;stream.destroy(err)}else if(isRequest(stream)){stream.abort()}else if(isRequest(stream.req)){stream.req.abort()}else if(typeof stream.destroy==="function"){stream.destroy(err)}else if(typeof stream.close==="function"){stream.close()}else if(err){process.nextTick(emitErrorCloseLegacy,stream,err)}else{process.nextTick(emitCloseLegacy,stream)}if(!stream.destroyed){stream[kDestroyed]=true}}module.exports={construct:construct,destroyer:destroyer,destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},{"../../ours/errors":39,"../../ours/primordials":40,"./utils":35,"process/":18}],24:[function(require,module,exports){"use strict";const{ObjectDefineProperties,ObjectGetOwnPropertyDescriptor,ObjectKeys,ObjectSetPrototypeOf}=require("../../ours/primordials");module.exports=Duplex;const Readable=require("./readable");const Writable=require("./writable");ObjectSetPrototypeOf(Duplex.prototype,Readable.prototype);ObjectSetPrototypeOf(Duplex,Readable);{const keys=ObjectKeys(Writable.prototype);for(let i=0;i{if(val!=null){throw new ERR_INVALID_RETURN_VALUE("nully","body",val)}},err=>{destroyer(d,err)});return d=new Duplexify({objectMode:true,readable:false,write:write,final(cb){final(async()=>{try{await promise;process.nextTick(cb,null)}catch(err){process.nextTick(cb,err)}})},destroy:destroy})}throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction",name,value)}if(isBlob(body)){return duplexify(body.arrayBuffer())}if(isIterable(body)){return from(Duplexify,body,{objectMode:true,writable:false})}if(typeof(body===null||body===undefined?undefined:body.writable)==="object"||typeof(body===null||body===undefined?undefined:body.readable)==="object"){const readable=body!==null&&body!==undefined&&body.readable?isReadableNodeStream(body===null||body===undefined?undefined:body.readable)?body===null||body===undefined?undefined:body.readable:duplexify(body.readable):undefined;const writable=body!==null&&body!==undefined&&body.writable?isWritableNodeStream(body===null||body===undefined?undefined:body.writable)?body===null||body===undefined?undefined:body.writable:duplexify(body.writable):undefined;return _duplexify({readable:readable,writable:writable})}const then=body===null||body===undefined?undefined:body.then;if(typeof then==="function"){let d;FunctionPrototypeCall(then,body,val=>{if(val!=null){d.push(val)}d.push(null)},err=>{destroyer(d,err)});return d=new Duplexify({objectMode:true,writable:false,read(){}})}throw new ERR_INVALID_ARG_TYPE(name,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],body)};function fromAsyncGen(fn){let{promise,resolve}=createDeferredPromise();const ac=new AbortController;const signal=ac.signal;const value=fn(async function*(){while(true){const _promise=promise;promise=null;const{chunk,done,cb}=await _promise;process.nextTick(cb);if(done)return;if(signal.aborted)throw new AbortError(undefined,{cause:signal.reason});({promise,resolve}=createDeferredPromise());yield chunk}}(),{signal:signal});return{value:value,write(chunk,encoding,cb){const _resolve=resolve;resolve=null;_resolve({chunk:chunk,done:false,cb:cb})},final(cb){const _resolve=resolve;resolve=null;_resolve({done:true,cb:cb})},destroy(err,cb){ac.abort();cb(err)}}}function _duplexify(pair){const r=pair.readable&&typeof pair.readable.read!=="function"?Readable.wrap(pair.readable):pair.readable;const w=pair.writable;let readable=!!isReadable(r);let writable=!!isWritable(w);let ondrain;let onfinish;let onreadable;let onclose;let d;function onfinished(err){const cb=onclose;onclose=null;if(cb){cb(err)}else if(err){d.destroy(err)}}d=new Duplexify({readableObjectMode:!!(r!==null&&r!==undefined&&r.readableObjectMode),writableObjectMode:!!(w!==null&&w!==undefined&&w.writableObjectMode),readable:readable,writable:writable});if(writable){eos(w,err=>{writable=false;if(err){destroyer(r,err)}onfinished(err)});d._write=function(chunk,encoding,callback){if(w.write(chunk,encoding)){callback()}else{ondrain=callback}};d._final=function(callback){w.end();onfinish=callback};w.on("drain",function(){if(ondrain){const cb=ondrain;ondrain=null;cb()}});w.on("finish",function(){if(onfinish){const cb=onfinish;onfinish=null;cb()}})}if(readable){eos(r,err=>{readable=false;if(err){destroyer(r,err)}onfinished(err)});r.on("readable",function(){if(onreadable){const cb=onreadable;onreadable=null;cb()}});r.on("end",function(){d.push(null)});d._read=function(){while(true){const buf=r.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf)){return}}}}d._destroy=function(err,callback){if(!err&&onclose!==null){err=new AbortError}onreadable=null;ondrain=null;onfinish=null;if(onclose===null){callback(err)}else{onclose=callback;destroyer(w,err);destroyer(r,err)}};return d}},{"../../ours/errors":39,"../../ours/primordials":40,"../../ours/util":41,"./destroy":23,"./duplex":24,"./end-of-stream":26,"./from":27,"./readable":32,"./utils":35,"abort-controller":11,buffer:15,"process/":18}],26:[function(require,module,exports){const process=require("process/");"use strict";const{AbortError,codes}=require("../../ours/errors");const{ERR_INVALID_ARG_TYPE,ERR_STREAM_PREMATURE_CLOSE}=codes;const{kEmptyObject,once}=require("../../ours/util");const{validateAbortSignal,validateFunction,validateObject,validateBoolean}=require("../validators");const{Promise,PromisePrototypeThen}=require("../../ours/primordials");const{isClosed,isReadable,isReadableNodeStream,isReadableStream,isReadableFinished,isReadableErrored,isWritable,isWritableNodeStream,isWritableStream,isWritableFinished,isWritableErrored,isNodeStream,willEmitClose:_willEmitClose,kIsClosedPromise}=require("./utils");function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"}const nop=()=>{};function eos(stream,options,callback){var _options$readable,_options$writable;if(arguments.length===2){callback=options;options=kEmptyObject}else if(options==null){options=kEmptyObject}else{validateObject(options,"options")}validateFunction(callback,"callback");validateAbortSignal(options.signal,"options.signal");callback=once(callback);if(isReadableStream(stream)||isWritableStream(stream)){return eosWeb(stream,options,callback)}if(!isNodeStream(stream)){throw new ERR_INVALID_ARG_TYPE("stream",["ReadableStream","WritableStream","Stream"],stream)}const readable=(_options$readable=options.readable)!==null&&_options$readable!==undefined?_options$readable:isReadableNodeStream(stream);const writable=(_options$writable=options.writable)!==null&&_options$writable!==undefined?_options$writable:isWritableNodeStream(stream);const wState=stream._writableState;const rState=stream._readableState;const onlegacyfinish=()=>{if(!stream.writable){onfinish()}};let willEmitClose=_willEmitClose(stream)&&isReadableNodeStream(stream)===readable&&isWritableNodeStream(stream)===writable;let writableFinished=isWritableFinished(stream,false);const onfinish=()=>{writableFinished=true;if(stream.destroyed){willEmitClose=false}if(willEmitClose&&(!stream.readable||readable)){return}if(!readable||readableFinished){callback.call(stream)}};let readableFinished=isReadableFinished(stream,false);const onend=()=>{readableFinished=true;if(stream.destroyed){willEmitClose=false}if(willEmitClose&&(!stream.writable||writable)){return}if(!writable||writableFinished){callback.call(stream)}};const onerror=err=>{callback.call(stream,err)};let closed=isClosed(stream);const onclose=()=>{closed=true;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!=="boolean"){return callback.call(stream,errored)}if(readable&&!readableFinished&&isReadableNodeStream(stream,true)){if(!isReadableFinished(stream,false))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}if(writable&&!writableFinished){if(!isWritableFinished(stream,false))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}callback.call(stream)};const onclosed=()=>{closed=true;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!=="boolean"){return callback.call(stream,errored)}callback.call(stream)};const onrequest=()=>{stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);if(!willEmitClose){stream.on("abort",onclose)}if(stream.req){onrequest()}else{stream.on("request",onrequest)}}else if(writable&&!wState){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}if(!willEmitClose&&typeof stream.aborted==="boolean"){stream.on("aborted",onclose)}stream.on("end",onend);stream.on("finish",onfinish);if(options.error!==false){stream.on("error",onerror)}stream.on("close",onclose);if(closed){process.nextTick(onclose)}else if(wState!==null&&wState!==undefined&&wState.errorEmitted||rState!==null&&rState!==undefined&&rState.errorEmitted){if(!willEmitClose){process.nextTick(onclosed)}}else if(!readable&&(!willEmitClose||isReadable(stream))&&(writableFinished||isWritable(stream)===false)){process.nextTick(onclosed)}else if(!writable&&(!willEmitClose||isWritable(stream))&&(readableFinished||isReadable(stream)===false)){process.nextTick(onclosed)}else if(rState&&stream.req&&stream.aborted){process.nextTick(onclosed)}const cleanup=()=>{callback=nop;stream.removeListener("aborted",onclose);stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("end",onend);stream.removeListener("error",onerror);stream.removeListener("close",onclose)};if(options.signal&&!closed){const abort=()=>{const endCallback=callback;cleanup();endCallback.call(stream,new AbortError(undefined,{cause:options.signal.reason}))};if(options.signal.aborted){process.nextTick(abort)}else{const originalCallback=callback;callback=once((...args)=>{options.signal.removeEventListener("abort",abort);originalCallback.apply(stream,args)});options.signal.addEventListener("abort",abort)}}return cleanup}function eosWeb(stream,options,callback){let isAborted=false;let abort=nop;if(options.signal){abort=()=>{isAborted=true;callback.call(stream,new AbortError(undefined,{cause:options.signal.reason}))};if(options.signal.aborted){process.nextTick(abort)}else{const originalCallback=callback;callback=once((...args)=>{options.signal.removeEventListener("abort",abort);originalCallback.apply(stream,args)});options.signal.addEventListener("abort",abort)}}const resolverFn=(...args)=>{if(!isAborted){process.nextTick(()=>callback.apply(stream,args))}};PromisePrototypeThen(stream[kIsClosedPromise].promise,resolverFn,resolverFn);return nop}function finished(stream,opts){var _opts;let autoCleanup=false;if(opts===null){opts=kEmptyObject}if((_opts=opts)!==null&&_opts!==undefined&&_opts.cleanup){validateBoolean(opts.cleanup,"cleanup");autoCleanup=opts.cleanup}return new Promise((resolve,reject)=>{const cleanup=eos(stream,opts,err=>{if(autoCleanup){cleanup()}if(err){reject(err)}else{resolve()}})})}module.exports=eos;module.exports.finished=finished},{"../../ours/errors":39,"../../ours/primordials":40,"../../ours/util":41,"../validators":37,"./utils":35,"process/":18}],27:[function(require,module,exports){"use strict";const process=require("process/");const{PromisePrototypeThen,SymbolAsyncIterator,SymbolIterator}=require("../../ours/primordials");const{Buffer}=require("buffer");const{ERR_INVALID_ARG_TYPE,ERR_STREAM_NULL_VALUES}=require("../../ours/errors").codes;function from(Readable,iterable,opts){let iterator;if(typeof iterable==="string"||iterable instanceof Buffer){return new Readable({objectMode:true,...opts,read(){this.push(iterable);this.push(null)}})}let isAsync;if(iterable&&iterable[SymbolAsyncIterator]){isAsync=true;iterator=iterable[SymbolAsyncIterator]()}else if(iterable&&iterable[SymbolIterator]){isAsync=false;iterator=iterable[SymbolIterator]()}else{throw new ERR_INVALID_ARG_TYPE("iterable",["Iterable"],iterable)}const readable=new Readable({objectMode:true,highWaterMark:1,...opts});let reading=false;readable._read=function(){if(!reading){reading=true;next()}};readable._destroy=function(error,cb){PromisePrototypeThen(close(error),()=>process.nextTick(cb,error),e=>process.nextTick(cb,e||error))};async function close(error){const hadError=error!==undefined&&error!==null;const hasThrow=typeof iterator.throw==="function";if(hadError&&hasThrow){const{value,done}=await iterator.throw(error);await value;if(done){return}}if(typeof iterator.return==="function"){const{value}=await iterator.return();await value}}async function next(){for(;;){try{const{value,done}=isAsync?await iterator.next():iterator.next();if(done){readable.push(null)}else{const res=value&&typeof value.then==="function"?await value:value;if(res===null){reading=false;throw new ERR_STREAM_NULL_VALUES}else if(readable.push(res)){continue}else{reading=false}}}catch(err){readable.destroy(err)}break}}return readable}module.exports=from},{"../../ours/errors":39,"../../ours/primordials":40,buffer:15,"process/":18}],28:[function(require,module,exports){"use strict";const{ArrayIsArray,ObjectSetPrototypeOf}=require("../../ours/primordials");const{EventEmitter:EE}=require("events");function Stream(opts){EE.call(this,opts)}ObjectSetPrototypeOf(Stream.prototype,EE.prototype);ObjectSetPrototypeOf(Stream,EE);Stream.prototype.pipe=function(dest,options){const source=this;function ondata(chunk){if(dest.writable&&dest.write(chunk)===false&&source.pause){source.pause()}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}let didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){this.emit("error",er)}}prependListener(source,"error",onerror);prependListener(dest,"error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest};function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function")return emitter.prependListener(event,fn);if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(ArrayIsArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}module.exports={Stream:Stream,prependListener:prependListener}},{"../../ours/primordials":40,events:16}],29:[function(require,module,exports){"use strict";const AbortController=globalThis.AbortController||require("abort-controller").AbortController;const{codes:{ERR_INVALID_ARG_VALUE,ERR_INVALID_ARG_TYPE,ERR_MISSING_ARGS,ERR_OUT_OF_RANGE},AbortError}=require("../../ours/errors");const{validateAbortSignal,validateInteger,validateObject}=require("../validators");const kWeakHandler=require("../../ours/primordials").Symbol("kWeak");const{finished}=require("./end-of-stream");const staticCompose=require("./compose");const{addAbortSignalNoValidate}=require("./add-abort-signal");const{isWritable,isNodeStream}=require("./utils");const{ArrayPrototypePush,MathFloor,Number,NumberIsNaN,Promise,PromiseReject,PromisePrototypeThen,Symbol}=require("../../ours/primordials");const kEmpty=Symbol("kEmpty");const kEof=Symbol("kEof");function compose(stream,options){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}if(isNodeStream(stream)&&!isWritable(stream)){throw new ERR_INVALID_ARG_VALUE("stream",stream,"must be writable")}const composedStream=staticCompose(this,stream);if(options!==null&&options!==undefined&&options.signal){addAbortSignalNoValidate(options.signal,composedStream)}return composedStream}function map(fn,options){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}let concurrency=1;if((options===null||options===undefined?undefined:options.concurrency)!=null){concurrency=MathFloor(options.concurrency)}validateInteger(concurrency,"concurrency",1);return async function*map(){var _options$signal,_options$signal2;const ac=new AbortController;const stream=this;const queue=[];const signal=ac.signal;const signalOpt={signal:signal};const abort=()=>ac.abort();if(options!==null&&options!==undefined&&(_options$signal=options.signal)!==null&&_options$signal!==undefined&&_options$signal.aborted){abort()}options===null||options===undefined?undefined:(_options$signal2=options.signal)===null||_options$signal2===undefined?undefined:_options$signal2.addEventListener("abort",abort);let next;let resume;let done=false;function onDone(){done=true}async function pump(){try{for await(let val of stream){var _val;if(done){return}if(signal.aborted){throw new AbortError}try{val=fn(val,signalOpt)}catch(err){val=PromiseReject(err)}if(val===kEmpty){continue}if(typeof((_val=val)===null||_val===undefined?undefined:_val.catch)==="function"){val.catch(onDone)}queue.push(val);if(next){next();next=null}if(!done&&queue.length&&queue.length>=concurrency){await new Promise(resolve=>{resume=resolve})}}queue.push(kEof)}catch(err){const val=PromiseReject(err);PromisePrototypeThen(val,undefined,onDone);queue.push(val)}finally{var _options$signal3;done=true;if(next){next();next=null}options===null||options===undefined?undefined:(_options$signal3=options.signal)===null||_options$signal3===undefined?undefined:_options$signal3.removeEventListener("abort",abort)}}pump();try{while(true){while(queue.length>0){const val=await queue[0];if(val===kEof){return}if(signal.aborted){throw new AbortError}if(val!==kEmpty){yield val}queue.shift();if(resume){resume();resume=null}}await new Promise(resolve=>{next=resolve})}}finally{ac.abort();done=true;if(resume){resume();resume=null}}}.call(this)}function asIndexedPairs(options=undefined){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}return async function*asIndexedPairs(){let index=0;for await(const val of this){var _options$signal4;if(options!==null&&options!==undefined&&(_options$signal4=options.signal)!==null&&_options$signal4!==undefined&&_options$signal4.aborted){throw new AbortError({cause:options.signal.reason})}yield[index++,val]}}.call(this)}async function some(fn,options=undefined){for await(const unused of filter.call(this,fn,options)){return true}return false}async function every(fn,options=undefined){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}return!await some.call(this,async(...args)=>{return!await fn(...args)},options)}async function find(fn,options){for await(const result of filter.call(this,fn,options)){return result}return undefined}async function forEach(fn,options){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}async function forEachFn(value,options){await fn(value,options);return kEmpty}for await(const unused of map.call(this,forEachFn,options));}function filter(fn,options){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}async function filterFn(value,options){if(await fn(value,options)){return value}return kEmpty}return map.call(this,filterFn,options)}class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function reduce(reducer,initialValue,options){var _options$signal5;if(typeof reducer!=="function"){throw new ERR_INVALID_ARG_TYPE("reducer",["Function","AsyncFunction"],reducer)}if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}let hasInitialValue=arguments.length>1;if(options!==null&&options!==undefined&&(_options$signal5=options.signal)!==null&&_options$signal5!==undefined&&_options$signal5.aborted){const err=new AbortError(undefined,{cause:options.signal.reason});this.once("error",()=>{});await finished(this.destroy(err));throw err}const ac=new AbortController;const signal=ac.signal;if(options!==null&&options!==undefined&&options.signal){const opts={once:true,[kWeakHandler]:this};options.signal.addEventListener("abort",()=>ac.abort(),opts)}let gotAnyItemFromStream=false;try{for await(const value of this){var _options$signal6;gotAnyItemFromStream=true;if(options!==null&&options!==undefined&&(_options$signal6=options.signal)!==null&&_options$signal6!==undefined&&_options$signal6.aborted){throw new AbortError}if(!hasInitialValue){initialValue=value;hasInitialValue=true}else{initialValue=await reducer(initialValue,value,{signal:signal})}}if(!gotAnyItemFromStream&&!hasInitialValue){throw new ReduceAwareErrMissingArgs}}finally{ac.abort()}return initialValue}async function toArray(options){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}const result=[];for await(const val of this){var _options$signal7;if(options!==null&&options!==undefined&&(_options$signal7=options.signal)!==null&&_options$signal7!==undefined&&_options$signal7.aborted){throw new AbortError(undefined,{cause:options.signal.reason})}ArrayPrototypePush(result,val)}return result}function flatMap(fn,options){const values=map.call(this,fn,options);return async function*flatMap(){for await(const val of values){yield*val}}.call(this)}function toIntegerOrInfinity(number){number=Number(number);if(NumberIsNaN(number)){return 0}if(number<0){throw new ERR_OUT_OF_RANGE("number",">= 0",number)}return number}function drop(number,options=undefined){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}number=toIntegerOrInfinity(number);return async function*drop(){var _options$signal8;if(options!==null&&options!==undefined&&(_options$signal8=options.signal)!==null&&_options$signal8!==undefined&&_options$signal8.aborted){throw new AbortError}for await(const val of this){var _options$signal9;if(options!==null&&options!==undefined&&(_options$signal9=options.signal)!==null&&_options$signal9!==undefined&&_options$signal9.aborted){throw new AbortError}if(number--<=0){yield val}}}.call(this)}function take(number,options=undefined){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}number=toIntegerOrInfinity(number);return async function*take(){var _options$signal10;if(options!==null&&options!==undefined&&(_options$signal10=options.signal)!==null&&_options$signal10!==undefined&&_options$signal10.aborted){throw new AbortError}for await(const val of this){var _options$signal11;if(options!==null&&options!==undefined&&(_options$signal11=options.signal)!==null&&_options$signal11!==undefined&&_options$signal11.aborted){throw new AbortError}if(number-- >0){yield val}else{return}}}.call(this)}module.exports.streamReturningOperators={asIndexedPairs:asIndexedPairs,drop:drop,filter:filter,flatMap:flatMap,map:map,take:take,compose:compose};module.exports.promiseReturningOperators={every:every,forEach:forEach,reduce:reduce,toArray:toArray,some:some,find:find}},{"../../ours/errors":39,"../../ours/primordials":40,"../validators":37,"./add-abort-signal":20,"./compose":22,"./end-of-stream":26,"./utils":35,"abort-controller":11}],30:[function(require,module,exports){"use strict";const{ObjectSetPrototypeOf}=require("../../ours/primordials");module.exports=PassThrough;const Transform=require("./transform");ObjectSetPrototypeOf(PassThrough.prototype,Transform.prototype);ObjectSetPrototypeOf(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"../../ours/primordials":40,"./transform":34}],31:[function(require,module,exports){const process=require("process/");"use strict";const{ArrayIsArray,Promise,SymbolAsyncIterator}=require("../../ours/primordials");const eos=require("./end-of-stream");const{once}=require("../../ours/util");const destroyImpl=require("./destroy");const Duplex=require("./duplex");const{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE,ERR_INVALID_RETURN_VALUE,ERR_MISSING_ARGS,ERR_STREAM_DESTROYED,ERR_STREAM_PREMATURE_CLOSE},AbortError}=require("../../ours/errors");const{validateFunction,validateAbortSignal}=require("../validators");const{isIterable,isReadable,isReadableNodeStream,isNodeStream,isTransformStream,isWebStream,isReadableStream,isReadableEnded}=require("./utils");const AbortController=globalThis.AbortController||require("abort-controller").AbortController;let PassThrough;let Readable;function destroyer(stream,reading,writing){let finished=false;stream.on("close",()=>{finished=true});const cleanup=eos(stream,{readable:reading,writable:writing},err=>{finished=!err});return{destroy:err=>{if(finished)return;finished=true;destroyImpl.destroyer(stream,err||new ERR_STREAM_DESTROYED("pipe"))},cleanup:cleanup}}function popCallback(streams){validateFunction(streams[streams.length-1],"streams[stream.length - 1]");return streams.pop()}function makeAsyncIterable(val){if(isIterable(val)){return val}else if(isReadableNodeStream(val)){return fromReadable(val)}throw new ERR_INVALID_ARG_TYPE("val",["Readable","Iterable","AsyncIterable"],val)}async function*fromReadable(val){if(!Readable){Readable=require("./readable")}yield*Readable.prototype[SymbolAsyncIterator].call(val)}async function pumpToNode(iterable,writable,finish,{end}){let error;let onresolve=null;const resume=err=>{if(err){error=err}if(onresolve){const callback=onresolve;onresolve=null;callback()}};const wait=()=>new Promise((resolve,reject)=>{if(error){reject(error)}else{onresolve=()=>{if(error){reject(error)}else{resolve()}}}});writable.on("drain",resume);const cleanup=eos(writable,{readable:false},resume);try{if(writable.writableNeedDrain){await wait()}for await(const chunk of iterable){if(!writable.write(chunk)){await wait()}}if(end){writable.end()}await wait();finish()}catch(err){finish(error!==err?aggregateTwoErrors(error,err):err)}finally{cleanup();writable.off("drain",resume)}}async function pumpToWeb(readable,writable,finish,{end}){if(isTransformStream(writable)){writable=writable.writable}const writer=writable.getWriter();try{for await(const chunk of readable){await writer.ready;writer.write(chunk).catch(()=>{})}await writer.ready;if(end){await writer.close()}finish()}catch(err){try{await writer.abort(err);finish(err)}catch(err){finish(err)}}}function pipeline(...streams){return pipelineImpl(streams,once(popCallback(streams)))}function pipelineImpl(streams,callback,opts){if(streams.length===1&&ArrayIsArray(streams[0])){streams=streams[0]}if(streams.length<2){throw new ERR_MISSING_ARGS("streams")}const ac=new AbortController;const signal=ac.signal;const outerSignal=opts===null||opts===undefined?undefined:opts.signal;const lastStreamCleanup=[];validateAbortSignal(outerSignal,"options.signal");function abort(){finishImpl(new AbortError)}outerSignal===null||outerSignal===undefined?undefined:outerSignal.addEventListener("abort",abort);let error;let value;const destroys=[];let finishCount=0;function finish(err){finishImpl(err,--finishCount===0)}function finishImpl(err,final){if(err&&(!error||error.code==="ERR_STREAM_PREMATURE_CLOSE")){error=err}if(!error&&!final){return}while(destroys.length){destroys.shift()(error)}outerSignal===null||outerSignal===undefined?undefined:outerSignal.removeEventListener("abort",abort);ac.abort();if(final){if(!error){lastStreamCleanup.forEach(fn=>fn())}process.nextTick(callback,error,value)}}let ret;for(let i=0;i0;const end=reading||(opts===null||opts===undefined?undefined:opts.end)!==false;const isLastStream=i===streams.length-1;if(isNodeStream(stream)){if(end){const{destroy,cleanup}=destroyer(stream,reading,writing);destroys.push(destroy);if(isReadable(stream)&&isLastStream){lastStreamCleanup.push(cleanup)}}function onError(err){if(err&&err.name!=="AbortError"&&err.code!=="ERR_STREAM_PREMATURE_CLOSE"){finish(err)}}stream.on("error",onError);if(isReadable(stream)&&isLastStream){lastStreamCleanup.push(()=>{stream.removeListener("error",onError)})}}if(i===0){if(typeof stream==="function"){ret=stream({signal:signal});if(!isIterable(ret)){throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream","source",ret)}}else if(isIterable(stream)||isReadableNodeStream(stream)||isTransformStream(stream)){ret=stream}else{ret=Duplex.from(stream)}}else if(typeof stream==="function"){if(isTransformStream(ret)){var _ret;ret=makeAsyncIterable((_ret=ret)===null||_ret===undefined?undefined:_ret.readable)}else{ret=makeAsyncIterable(ret)}ret=stream(ret,{signal:signal});if(reading){if(!isIterable(ret,true)){throw new ERR_INVALID_RETURN_VALUE("AsyncIterable",`transform[${i-1}]`,ret)}}else{var _ret2;if(!PassThrough){PassThrough=require("./passthrough")}const pt=new PassThrough({objectMode:true});const then=(_ret2=ret)===null||_ret2===undefined?undefined:_ret2.then;if(typeof then==="function"){finishCount++;then.call(ret,val=>{value=val;if(val!=null){pt.write(val)}if(end){pt.end()}process.nextTick(finish)},err=>{pt.destroy(err);process.nextTick(finish,err)})}else if(isIterable(ret,true)){finishCount++;pumpToNode(ret,pt,finish,{end:end})}else if(isReadableStream(ret)||isTransformStream(ret)){const toRead=ret.readable||ret;finishCount++;pumpToNode(toRead,pt,finish,{end:end})}else{throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise","destination",ret)}ret=pt;const{destroy,cleanup}=destroyer(ret,false,true);destroys.push(destroy);if(isLastStream){lastStreamCleanup.push(cleanup)}}}else if(isNodeStream(stream)){if(isReadableNodeStream(ret)){finishCount+=2;const cleanup=pipe(ret,stream,finish,{end:end});if(isReadable(stream)&&isLastStream){lastStreamCleanup.push(cleanup)}}else if(isTransformStream(ret)||isReadableStream(ret)){const toRead=ret.readable||ret;finishCount++;pumpToNode(toRead,stream,finish,{end:end})}else if(isIterable(ret)){finishCount++;pumpToNode(ret,stream,finish,{end:end})}else{throw new ERR_INVALID_ARG_TYPE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ret)}ret=stream}else if(isWebStream(stream)){if(isReadableNodeStream(ret)){finishCount++;pumpToWeb(makeAsyncIterable(ret),stream,finish,{end:end})}else if(isReadableStream(ret)||isIterable(ret)){finishCount++;pumpToWeb(ret,stream,finish,{end:end})}else if(isTransformStream(ret)){finishCount++;pumpToWeb(ret.readable,stream,finish,{end:end})}else{throw new ERR_INVALID_ARG_TYPE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ret)}ret=stream}else{ret=Duplex.from(stream)}}if(signal!==null&&signal!==undefined&&signal.aborted||outerSignal!==null&&outerSignal!==undefined&&outerSignal.aborted){process.nextTick(abort)}return ret}function pipe(src,dst,finish,{end}){let ended=false;dst.on("close",()=>{if(!ended){finish(new ERR_STREAM_PREMATURE_CLOSE)}});src.pipe(dst,{end:false});if(end){function endFn(){ended=true;dst.end()}if(isReadableEnded(src)){process.nextTick(endFn)}else{src.once("end",endFn)}}else{finish()}eos(src,{readable:true,writable:false},err=>{const rState=src._readableState;if(err&&err.code==="ERR_STREAM_PREMATURE_CLOSE"&&rState&&rState.ended&&!rState.errored&&!rState.errorEmitted){src.once("end",finish).once("error",finish)}else{finish(err)}});return eos(dst,{readable:false,writable:true},finish)}module.exports={pipelineImpl:pipelineImpl,pipeline:pipeline}},{"../../ours/errors":39,"../../ours/primordials":40,"../../ours/util":41,"../validators":37,"./destroy":23,"./duplex":24,"./end-of-stream":26,"./passthrough":30,"./readable":32,"./utils":35,"abort-controller":11,"process/":18}],32:[function(require,module,exports){const process=require("process/");"use strict";const{ArrayPrototypeIndexOf,NumberIsInteger,NumberIsNaN,NumberParseInt,ObjectDefineProperties,ObjectKeys,ObjectSetPrototypeOf,Promise,SafeSet,SymbolAsyncIterator,Symbol}=require("../../ours/primordials");module.exports=Readable;Readable.ReadableState=ReadableState;const{EventEmitter:EE}=require("events");const{Stream,prependListener}=require("./legacy");const{Buffer}=require("buffer");const{addAbortSignal}=require("./add-abort-signal");const eos=require("./end-of-stream");let debug=require("../../ours/util").debuglog("stream",fn=>{debug=fn});const BufferList=require("./buffer_list");const destroyImpl=require("./destroy");const{getHighWaterMark,getDefaultHighWaterMark}=require("./state");const{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED,ERR_OUT_OF_RANGE,ERR_STREAM_PUSH_AFTER_EOF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT}}=require("../../ours/errors");const{validateObject}=require("../validators");const kPaused=Symbol("kPaused");const{StringDecoder}=require("string_decoder");const from=require("./from");ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);ObjectSetPrototypeOf(Readable,Stream);const nop=()=>{};const{errorOrDestroy}=destroyImpl;function ReadableState(options,stream,isDuplex){if(typeof isDuplex!=="boolean")isDuplex=stream instanceof require("./duplex");this.objectMode=!!(options&&options.objectMode);if(isDuplex)this.objectMode=this.objectMode||!!(options&&options.readableObjectMode);this.highWaterMark=options?getHighWaterMark(this,options,"readableHighWaterMark",isDuplex):getDefaultHighWaterMark(false);this.buffer=new BufferList;this.length=0;this.pipes=[];this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.constructed=true;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this[kPaused]=null;this.errorEmitted=false;this.emitClose=!options||options.emitClose!==false;this.autoDestroy=!options||options.autoDestroy!==false;this.destroyed=false;this.errored=null;this.closed=false;this.closeEmitted=false;this.defaultEncoding=options&&options.defaultEncoding||"utf8";this.awaitDrainWriters=null;this.multiAwaitDrain=false;this.readingMore=false;this.dataEmitted=false;this.decoder=null;this.encoding=null;if(options&&options.encoding){this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);const isDuplex=this instanceof require("./duplex");this._readableState=new ReadableState(options,this,isDuplex);if(options){if(typeof options.read==="function")this._read=options.read;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options.construct==="function")this._construct=options.construct;if(options.signal&&!isDuplex)addAbortSignal(options.signal,this)}Stream.call(this,options);destroyImpl.construct(this,()=>{if(this._readableState.needReadable){maybeReadMore(this,this._readableState)}})}Readable.prototype.destroy=destroyImpl.destroy;Readable.prototype._undestroy=destroyImpl.undestroy;Readable.prototype._destroy=function(err,cb){cb(err)};Readable.prototype[EE.captureRejectionSymbol]=function(err){this.destroy(err)};Readable.prototype.push=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,false)};Readable.prototype.unshift=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,true)};function readableAddChunk(stream,chunk,encoding,addToFront){debug("readableAddChunk",chunk);const state=stream._readableState;let err;if(!state.objectMode){if(typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(state.encoding!==encoding){if(addToFront&&state.encoding){chunk=Buffer.from(chunk,encoding).toString(state.encoding)}else{chunk=Buffer.from(chunk,encoding);encoding=""}}}else if(chunk instanceof Buffer){encoding=""}else if(Stream._isUint8Array(chunk)){chunk=Stream._uint8ArrayToBuffer(chunk);encoding=""}else if(chunk!=null){err=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)}}if(err){errorOrDestroy(stream,err)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(addToFront){if(state.endEmitted)errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else if(state.destroyed||state.errored)return false;else addChunk(stream,state,chunk,true)}else if(state.ended){errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF)}else if(state.destroyed||state.errored){return false}else{state.reading=false;if(state.decoder&&!encoding){chunk=state.decoder.write(chunk);if(state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,false);else maybeReadMore(stream,state)}else{addChunk(stream,state,chunk,false)}}}else if(!addToFront){state.reading=false;maybeReadMore(stream,state)}return!state.ended&&(state.length0){if(state.multiAwaitDrain){state.awaitDrainWriters.clear()}else{state.awaitDrainWriters=null}state.dataEmitted=true;stream.emit("data",chunk)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}maybeReadMore(stream,state)}Readable.prototype.isPaused=function(){const state=this._readableState;return state[kPaused]===true||state.flowing===false};Readable.prototype.setEncoding=function(enc){const decoder=new StringDecoder(enc);this._readableState.decoder=decoder;this._readableState.encoding=this._readableState.decoder.encoding;const buffer=this._readableState.buffer;let content="";for(const data of buffer){content+=decoder.write(data)}buffer.clear();if(content!=="")buffer.push(content);this._readableState.length=content.length;return this};const MAX_HWM=1073741824;function computeNewHighWaterMark(n){if(n>MAX_HWM){throw new ERR_OUT_OF_RANGE("size","<= 1GiB",n)}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(NumberIsNaN(n)){if(state.flowing&&state.length)return state.buffer.first().length;return state.length}if(n<=state.length)return n;return state.ended?state.length:0}Readable.prototype.read=function(n){debug("read",n);if(n===undefined){n=NaN}else if(!NumberIsInteger(n)){n=NumberParseInt(n,10)}const state=this._readableState;const nOrig=n;if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&((state.highWaterMark!==0?state.length>=state.highWaterMark:state.length>0)||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}let doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=state.length<=state.highWaterMark;n=0}else{state.length-=n;if(state.multiAwaitDrain){state.awaitDrainWriters.clear()}else{state.awaitDrainWriters=null}}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null&&!state.errorEmitted&&!state.closeEmitted){state.dataEmitted=true;this.emit("data",ret)}return ret};function onEofChunk(stream,state){debug("onEofChunk");if(state.ended)return;if(state.decoder){const chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.sync){emitReadable(stream)}else{state.needReadable=false;state.emittedReadable=true;emitReadable_(stream)}}function emitReadable(stream){const state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable);state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;process.nextTick(emitReadable_,stream)}}function emitReadable_(stream){const state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended);if(!state.destroyed&&!state.errored&&(state.length||state.ended)){stream.emit("readable");state.emittedReadable=false}state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark;flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore&&state.constructed){state.readingMore=true;process.nextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){while(!state.reading&&!state.ended&&(state.length1&&state.pipes.includes(dest)){debug("false write response, pause",state.awaitDrainWriters.size);state.awaitDrainWriters.add(dest)}src.pause()}if(!ondrain){ondrain=pipeOnDrain(src,dest);dest.on("drain",ondrain)}}src.on("data",ondata);function ondata(chunk){debug("ondata");const ret=dest.write(chunk);debug("dest.write",ret);if(ret===false){pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(dest.listenerCount("error")===0){const s=dest._writableState||dest._readableState;if(s&&!s.errorEmitted){errorOrDestroy(dest,er)}else{dest.emit("error",er)}}}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(dest.writableNeedDrain===true){if(state.flowing){pause()}}else if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src,dest){return function pipeOnDrainFunctionResult(){const state=src._readableState;if(state.awaitDrainWriters===dest){debug("pipeOnDrain",1);state.awaitDrainWriters=null}else if(state.multiAwaitDrain){debug("pipeOnDrain",state.awaitDrainWriters.size);state.awaitDrainWriters.delete(dest)}if((!state.awaitDrainWriters||state.awaitDrainWriters.size===0)&&src.listenerCount("data")){src.resume()}}}Readable.prototype.unpipe=function(dest){const state=this._readableState;const unpipeInfo={hasUnpiped:false};if(state.pipes.length===0)return this;if(!dest){const dests=state.pipes;state.pipes=[];this.pause();for(let i=0;i0;if(state.flowing!==false)this.resume()}else if(ev==="readable"){if(!state.endEmitted&&!state.readableListening){state.readableListening=state.needReadable=true;state.flowing=false;state.emittedReadable=false;debug("on readable",state.length,state.reading);if(state.length){emitReadable(this)}else if(!state.reading){process.nextTick(nReadingNextTick,this)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(ev,fn){const res=Stream.prototype.removeListener.call(this,ev,fn);if(ev==="readable"){process.nextTick(updateReadableListening,this)}return res};Readable.prototype.off=Readable.prototype.removeListener;Readable.prototype.removeAllListeners=function(ev){const res=Stream.prototype.removeAllListeners.apply(this,arguments);if(ev==="readable"||ev===undefined){process.nextTick(updateReadableListening,this)}return res};function updateReadableListening(self){const state=self._readableState;state.readableListening=self.listenerCount("readable")>0;if(state.resumeScheduled&&state[kPaused]===false){state.flowing=true}else if(self.listenerCount("data")>0){self.resume()}else if(!state.readableListening){state.flowing=null}}function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}Readable.prototype.resume=function(){const state=this._readableState;if(!state.flowing){debug("resume");state.flowing=!state.readableListening;resume(this,state)}state[kPaused]=false;return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;process.nextTick(resume_,stream,state)}}function resume_(stream,state){debug("resume",state.reading);if(!state.reading){stream.read(0)}state.resumeScheduled=false;stream.emit("resume");flow(stream);if(state.flowing&&!state.reading)stream.read(0)}Readable.prototype.pause=function(){debug("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){debug("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState[kPaused]=true;return this};function flow(stream){const state=stream._readableState;debug("flow",state.flowing);while(state.flowing&&stream.read()!==null);}Readable.prototype.wrap=function(stream){let paused=false;stream.on("data",chunk=>{if(!this.push(chunk)&&stream.pause){paused=true;stream.pause()}});stream.on("end",()=>{this.push(null)});stream.on("error",err=>{errorOrDestroy(this,err)});stream.on("close",()=>{this.destroy()});stream.on("destroy",()=>{this.destroy()});this._read=()=>{if(paused&&stream.resume){paused=false;stream.resume()}};const streamKeys=ObjectKeys(stream);for(let j=1;j{error=err?aggregateTwoErrors(error,err):null;callback();callback=nop});try{while(true){const chunk=stream.destroyed?null:stream.read();if(chunk!==null){yield chunk}else if(error){throw error}else if(error===null){return}else{await new Promise(next)}}}catch(err){error=aggregateTwoErrors(error,err);throw error}finally{if((error||(options===null||options===undefined?undefined:options.destroyOnReturn)!==false)&&(error===undefined||stream._readableState.autoDestroy)){destroyImpl.destroyer(stream,null)}else{stream.off("readable",next);cleanup()}}}ObjectDefineProperties(Readable.prototype,{readable:{__proto__:null,get(){const r=this._readableState;return!!r&&r.readable!==false&&!r.destroyed&&!r.errorEmitted&&!r.endEmitted},set(val){if(this._readableState){this._readableState.readable=!!val}}},readableDidRead:{__proto__:null,enumerable:false,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:false,get:function(){return!!(this._readableState.readable!==false&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:false,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:false,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:false,get:function(){return this._readableState.flowing},set:function(state){if(this._readableState){this._readableState.flowing=state}}},readableLength:{__proto__:null,enumerable:false,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.objectMode:false}},readableEncoding:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:false}},destroyed:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.destroyed:false},set(value){if(!this._readableState){return}this._readableState.destroyed=value}},readableEnded:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.endEmitted:false}}});ObjectDefineProperties(ReadableState.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[kPaused]!==false},set(value){this[kPaused]=!!value}}});Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;let ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=state.buffer.consume(n,state.decoder)}return ret}function endReadable(stream){const state=stream._readableState;debug("endReadable",state.endEmitted);if(!state.endEmitted){state.ended=true;process.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){debug("endReadableNT",state.endEmitted,state.length);if(!state.errored&&!state.closeEmitted&&!state.endEmitted&&state.length===0){state.endEmitted=true;stream.emit("end");if(stream.writable&&stream.allowHalfOpen===false){process.nextTick(endWritableNT,stream)}else if(state.autoDestroy){const wState=stream._writableState;const autoDestroy=!wState||wState.autoDestroy&&(wState.finished||wState.writable===false);if(autoDestroy){stream.destroy()}}}}function endWritableNT(stream){const writable=stream.writable&&!stream.writableEnded&&!stream.destroyed;if(writable){stream.end()}}Readable.from=function(iterable,opts){return from(Readable,iterable,opts)};let webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===undefined)webStreamsAdapters={};return webStreamsAdapters}Readable.fromWeb=function(readableStream,options){return lazyWebStreams().newStreamReadableFromReadableStream(readableStream,options)};Readable.toWeb=function(streamReadable,options){return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable,options)};Readable.wrap=function(src,options){var _ref,_src$readableObjectMo;return new Readable({objectMode:(_ref=(_src$readableObjectMo=src.readableObjectMode)!==null&&_src$readableObjectMo!==undefined?_src$readableObjectMo:src.objectMode)!==null&&_ref!==undefined?_ref:true,...options,destroy(err,callback){destroyImpl.destroyer(src,err);callback(err)}}).wrap(src)}},{"../../ours/errors":39,"../../ours/primordials":40,"../../ours/util":41,"../validators":37,"./add-abort-signal":20,"./buffer_list":21,"./destroy":23,"./duplex":24,"./end-of-stream":26,"./from":27,"./legacy":28,"./state":33,buffer:15,events:16,"process/":18,string_decoder:14}],33:[function(require,module,exports){"use strict";const{MathFloor,NumberIsInteger}=require("../../ours/primordials");const{ERR_INVALID_ARG_VALUE}=require("../../ours/errors").codes;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null?options.highWaterMark:isDuplex?options[duplexKey]:null}function getDefaultHighWaterMark(objectMode){return objectMode?16:16*1024}function getHighWaterMark(state,options,duplexKey,isDuplex){const hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!NumberIsInteger(hwm)||hwm<0){const name=isDuplex?`options.${duplexKey}`:"options.highWaterMark";throw new ERR_INVALID_ARG_VALUE(name,hwm)}return MathFloor(hwm)}return getDefaultHighWaterMark(state.objectMode)}module.exports={getHighWaterMark:getHighWaterMark,getDefaultHighWaterMark:getDefaultHighWaterMark}},{"../../ours/errors":39,"../../ours/primordials":40}],34:[function(require,module,exports){"use strict";const{ObjectSetPrototypeOf,Symbol}=require("../../ours/primordials");module.exports=Transform;const{ERR_METHOD_NOT_IMPLEMENTED}=require("../../ours/errors").codes;const Duplex=require("./duplex");const{getHighWaterMark}=require("./state");ObjectSetPrototypeOf(Transform.prototype,Duplex.prototype);ObjectSetPrototypeOf(Transform,Duplex);const kCallback=Symbol("kCallback");function Transform(options){if(!(this instanceof Transform))return new Transform(options);const readableHighWaterMark=options?getHighWaterMark(this,options,"readableHighWaterMark",true):null;if(readableHighWaterMark===0){options={...options,highWaterMark:null,readableHighWaterMark:readableHighWaterMark,writableHighWaterMark:options.writableHighWaterMark||0}}Duplex.call(this,options);this._readableState.sync=false;this[kCallback]=null;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}this.on("prefinish",prefinish)}function final(cb){if(typeof this._flush==="function"&&!this.destroyed){this._flush((er,data)=>{if(er){if(cb){cb(er)}else{this.destroy(er)}return}if(data!=null){this.push(data)}this.push(null);if(cb){cb()}})}else{this.push(null);if(cb){cb()}}}function prefinish(){if(this._final!==final){final.call(this)}}Transform.prototype._final=final;Transform.prototype._transform=function(chunk,encoding,callback){throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()")};Transform.prototype._write=function(chunk,encoding,callback){const rState=this._readableState;const wState=this._writableState;const length=rState.length;this._transform(chunk,encoding,(err,val)=>{if(err){callback(err);return}if(val!=null){this.push(val)}if(wState.ended||length===rState.length||rState.length{const state=this._writableState;if(!state.writing){clearBuffer(this,state)}finishMaybe(this,state)})}ObjectDefineProperty(Writable,SymbolHasInstance,{__proto__:null,value:function(object){if(FunctionPrototypeSymbolHasInstance(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}});Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)};function _write(stream,chunk,encoding,cb){const state=stream._writableState;if(typeof encoding==="function"){cb=encoding;encoding=state.defaultEncoding}else{if(!encoding)encoding=state.defaultEncoding;else if(encoding!=="buffer"&&!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);if(typeof cb!=="function")cb=nop}if(chunk===null){throw new ERR_STREAM_NULL_VALUES}else if(!state.objectMode){if(typeof chunk==="string"){if(state.decodeStrings!==false){chunk=Buffer.from(chunk,encoding);encoding="buffer"}}else if(chunk instanceof Buffer){encoding="buffer"}else if(Stream._isUint8Array(chunk)){chunk=Stream._uint8ArrayToBuffer(chunk);encoding="buffer"}else{throw new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)}}let err;if(state.ending){err=new ERR_STREAM_WRITE_AFTER_END}else if(state.destroyed){err=new ERR_STREAM_DESTROYED("write")}if(err){process.nextTick(cb,err);errorOrDestroy(stream,err,true);return err}state.pendingcb++;return writeOrBuffer(stream,state,chunk,encoding,cb)}Writable.prototype.write=function(chunk,encoding,cb){return _write(this,chunk,encoding,cb)===true};Writable.prototype.cork=function(){this._writableState.corked++};Writable.prototype.uncork=function(){const state=this._writableState;if(state.corked){state.corked--;if(!state.writing)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=StringPrototypeToLowerCase(encoding);if(!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);this._writableState.defaultEncoding=encoding;return this};function writeOrBuffer(stream,state,chunk,encoding,callback){const len=state.objectMode?1:chunk.length;state.length+=len;const ret=state.lengthstate.bufferedIndex){clearBuffer(stream,state)}if(sync){if(state.afterWriteTickInfo!==null&&state.afterWriteTickInfo.cb===cb){state.afterWriteTickInfo.count++}else{state.afterWriteTickInfo={count:1,cb:cb,stream:stream,state:state};process.nextTick(afterWriteTick,state.afterWriteTickInfo)}}else{afterWrite(stream,state,1,cb)}}}function afterWriteTick({stream,state,count,cb}){state.afterWriteTickInfo=null;return afterWrite(stream,state,count,cb)}function afterWrite(stream,state,count,cb){const needDrain=!state.ending&&!stream.destroyed&&state.length===0&&state.needDrain;if(needDrain){state.needDrain=false;stream.emit("drain")}while(count-- >0){state.pendingcb--;cb()}if(state.destroyed){errorBuffer(state)}finishMaybe(stream,state)}function errorBuffer(state){if(state.writing){return}for(let n=state.bufferedIndex;n1&&stream._writev){state.pendingcb-=bufferedLength-1;const callback=state.allNoop?nop:err=>{for(let n=i;n256){buffered.splice(0,i);state.bufferedIndex=0}else{state.bufferedIndex=i}}state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){if(this._writev){this._writev([{chunk:chunk,encoding:encoding}],cb)}else{throw new ERR_METHOD_NOT_IMPLEMENTED("_write()")}};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){const state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}let err;if(chunk!==null&&chunk!==undefined){const ret=_write(this,chunk,encoding);if(ret instanceof Error){err=ret}}if(state.corked){state.corked=1;this.uncork()}if(err){}else if(!state.errored&&!state.ending){state.ending=true;finishMaybe(this,state,true);state.ended=true}else if(state.finished){err=new ERR_STREAM_ALREADY_FINISHED("end")}else if(state.destroyed){err=new ERR_STREAM_DESTROYED("end")}if(typeof cb==="function"){if(err||state.finished){process.nextTick(cb,err)}else{state[kOnFinished].push(cb)}}return this};function needFinish(state){return state.ending&&!state.destroyed&&state.constructed&&state.length===0&&!state.errored&&state.buffered.length===0&&!state.finished&&!state.writing&&!state.errorEmitted&&!state.closeEmitted}function callFinal(stream,state){let called=false;function onFinish(err){if(called){errorOrDestroy(stream,err!==null&&err!==undefined?err:ERR_MULTIPLE_CALLBACK());return}called=true;state.pendingcb--;if(err){const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(needFinish(state)){finish(stream,state)}else{state.pendingcb--}},stream,state)}else if(needFinish(state)){state.pendingcb++;finish(stream,state)}}}}function finish(stream,state){state.pendingcb--;state.finished=true;const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i>>0}const octalReg=/^[0-7]+$/;const modeDesc="must be a 32-bit unsigned integer or an octal string";function parseFileMode(value,name,def){if(typeof value==="undefined"){value=def}if(typeof value==="string"){if(RegExpPrototypeExec(octalReg,value)===null){throw new ERR_INVALID_ARG_VALUE(name,value,modeDesc)}value=NumberParseInt(value,8)}validateUint32(value,name);return value}const validateInteger=hideStackFrames((value,name,min=NumberMIN_SAFE_INTEGER,max=NumberMAX_SAFE_INTEGER)=>{if(typeof value!=="number")throw new ERR_INVALID_ARG_TYPE(name,"number",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,"an integer",value);if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)});const validateInt32=hideStackFrames((value,name,min=-2147483648,max=2147483647)=>{if(typeof value!=="number"){throw new ERR_INVALID_ARG_TYPE(name,"number",value)}if(!NumberIsInteger(value)){throw new ERR_OUT_OF_RANGE(name,"an integer",value)}if(valuemax){throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}});const validateUint32=hideStackFrames((value,name,positive=false)=>{if(typeof value!=="number"){throw new ERR_INVALID_ARG_TYPE(name,"number",value)}if(!NumberIsInteger(value)){throw new ERR_OUT_OF_RANGE(name,"an integer",value)}const min=positive?1:0;const max=4294967295;if(valuemax){throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}});function validateString(value,name){if(typeof value!=="string")throw new ERR_INVALID_ARG_TYPE(name,"string",value)}function validateNumber(value,name,min=undefined,max){if(typeof value!=="number")throw new ERR_INVALID_ARG_TYPE(name,"number",value);if(min!=null&&valuemax||(min!=null||max!=null)&&NumberIsNaN(value)){throw new ERR_OUT_OF_RANGE(name,`${min!=null?`>= ${min}`:""}${min!=null&&max!=null?" && ":""}${max!=null?`<= ${max}`:""}`,value)}}const validateOneOf=hideStackFrames((value,name,oneOf)=>{if(!ArrayPrototypeIncludes(oneOf,value)){const allowed=ArrayPrototypeJoin(ArrayPrototypeMap(oneOf,v=>typeof v==="string"?`'${v}'`:String(v)),", ");const reason="must be one of: "+allowed;throw new ERR_INVALID_ARG_VALUE(name,value,reason)}});function validateBoolean(value,name){if(typeof value!=="boolean")throw new ERR_INVALID_ARG_TYPE(name,"boolean",value)}function getOwnPropertyValueOrDefault(options,key,defaultValue){return options==null||!ObjectPrototypeHasOwnProperty(options,key)?defaultValue:options[key]}const validateObject=hideStackFrames((value,name,options=null)=>{const allowArray=getOwnPropertyValueOrDefault(options,"allowArray",false);const allowFunction=getOwnPropertyValueOrDefault(options,"allowFunction",false);const nullable=getOwnPropertyValueOrDefault(options,"nullable",false);if(!nullable&&value===null||!allowArray&&ArrayIsArray(value)||typeof value!=="object"&&(!allowFunction||typeof value!=="function")){throw new ERR_INVALID_ARG_TYPE(name,"Object",value)}});const validateDictionary=hideStackFrames((value,name)=>{if(value!=null&&typeof value!=="object"&&typeof value!=="function"){throw new ERR_INVALID_ARG_TYPE(name,"a dictionary",value)}});const validateArray=hideStackFrames((value,name,minLength=0)=>{if(!ArrayIsArray(value)){throw new ERR_INVALID_ARG_TYPE(name,"Array",value)}if(value.length{if(!isArrayBufferView(buffer)){throw new ERR_INVALID_ARG_TYPE(name,["Buffer","TypedArray","DataView"],buffer)}});function validateEncoding(data,encoding){const normalizedEncoding=normalizeEncoding(encoding);const length=data.length;if(normalizedEncoding==="hex"&&length%2!==0){throw new ERR_INVALID_ARG_VALUE("encoding",encoding,`is invalid for data of length ${length}`)}}function validatePort(port,name="Port",allowZero=true){if(typeof port!=="number"&&typeof port!=="string"||typeof port==="string"&&StringPrototypeTrim(port).length===0||+port!==+port>>>0||port>65535||port===0&&!allowZero){throw new ERR_SOCKET_BAD_PORT(name,port,allowZero)}return port|0}const validateAbortSignal=hideStackFrames((signal,name)=>{if(signal!==undefined&&(signal===null||typeof signal!=="object"||!("aborted"in signal))){throw new ERR_INVALID_ARG_TYPE(name,"AbortSignal",signal)}});const validateFunction=hideStackFrames((value,name)=>{if(typeof value!=="function")throw new ERR_INVALID_ARG_TYPE(name,"Function",value)});const validatePlainFunction=hideStackFrames((value,name)=>{if(typeof value!=="function"||isAsyncFunction(value))throw new ERR_INVALID_ARG_TYPE(name,"Function",value)});const validateUndefined=hideStackFrames((value,name)=>{if(value!==undefined)throw new ERR_INVALID_ARG_TYPE(name,"undefined",value)});function validateUnion(value,name,union){if(!ArrayPrototypeIncludes(union,value)){throw new ERR_INVALID_ARG_TYPE(name,`('${ArrayPrototypeJoin(union,"|")}')`,value)}}const linkValueRegExp=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function validateLinkHeaderFormat(value,name){if(typeof value==="undefined"||!RegExpPrototypeExec(linkValueRegExp,value)){throw new ERR_INVALID_ARG_VALUE(name,value,'must be an array or string of format "; rel=preload; as=style"')}}function validateLinkHeaderValue(hints){if(typeof hints==="string"){validateLinkHeaderFormat(hints,"hints");return hints}else if(ArrayIsArray(hints)){const hintsLength=hints.length;let result="";if(hintsLength===0){return result}for(let i=0;i; rel=preload; as=style"')}module.exports={isInt32:isInt32,isUint32:isUint32,parseFileMode:parseFileMode,validateArray:validateArray,validateStringArray:validateStringArray,validateBooleanArray:validateBooleanArray,validateBoolean:validateBoolean,validateBuffer:validateBuffer,validateDictionary:validateDictionary,validateEncoding:validateEncoding,validateFunction:validateFunction,validateInt32:validateInt32,validateInteger:validateInteger,validateNumber:validateNumber,validateObject:validateObject,validateOneOf:validateOneOf,validatePlainFunction:validatePlainFunction,validatePort:validatePort,validateSignalName:validateSignalName,validateString:validateString,validateUint32:validateUint32,validateUndefined:validateUndefined,validateUnion:validateUnion,validateAbortSignal:validateAbortSignal,validateLinkHeaderValue:validateLinkHeaderValue}},{"../ours/errors":39,"../ours/primordials":40,"../ours/util":41}],38:[function(require,module,exports){"use strict";const CustomStream=require("../stream");const promises=require("../stream/promises");const originalDestroy=CustomStream.Readable.destroy;module.exports=CustomStream.Readable;module.exports._uint8ArrayToBuffer=CustomStream._uint8ArrayToBuffer;module.exports._isUint8Array=CustomStream._isUint8Array;module.exports.isDisturbed=CustomStream.isDisturbed;module.exports.isErrored=CustomStream.isErrored;module.exports.isReadable=CustomStream.isReadable;module.exports.Readable=CustomStream.Readable;module.exports.Writable=CustomStream.Writable;module.exports.Duplex=CustomStream.Duplex;module.exports.Transform=CustomStream.Transform;module.exports.PassThrough=CustomStream.PassThrough;module.exports.addAbortSignal=CustomStream.addAbortSignal;module.exports.finished=CustomStream.finished;module.exports.destroy=CustomStream.destroy;module.exports.destroy=originalDestroy;module.exports.pipeline=CustomStream.pipeline;module.exports.compose=CustomStream.compose;Object.defineProperty(CustomStream,"promises",{configurable:true,enumerable:true,get(){return promises}});module.exports.Stream=CustomStream.Stream;module.exports.default=module.exports},{"../stream":42,"../stream/promises":43}],39:[function(require,module,exports){"use strict";const{format,inspect,AggregateError:CustomAggregateError}=require("./util");const AggregateError=globalThis.AggregateError||CustomAggregateError;const kIsNodeError=Symbol("kIsNodeError");const kTypes=["string","function","number","object","Function","Object","boolean","bigint","symbol"];const classRegExp=/^([A-Z][a-z0-9]*)+$/;const nodeInternalPrefix="__node_internal_";const codes={};function assert(value,message){if(!value){throw new codes.ERR_INTERNAL_ASSERTION(message)}}function addNumericalSeparator(val){let res="";let i=val.length;const start=val[0]==="-"?1:0;for(;i>=start+4;i-=3){res=`_${val.slice(i-3,i)}${res}`}return`${val.slice(0,i)}${res}`}function getMessage(key,msg,args){if(typeof msg==="function"){assert(msg.length<=args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`);return msg(...args)}const expectedLength=(msg.match(/%[dfijoOs]/g)||[]).length;assert(expectedLength===args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`);if(args.length===0){return msg}return format(msg,...args)}function E(code,message,Base){if(!Base){Base=Error}class NodeError extends Base{constructor(...args){super(getMessage(code,message,args))}toString(){return`${this.name} [${code}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:Base.name,writable:true,enumerable:false,configurable:true},toString:{value(){return`${this.name} [${code}]: ${this.message}`},writable:true,enumerable:false,configurable:true}});NodeError.prototype.code=code;NodeError.prototype[kIsNodeError]=true;codes[code]=NodeError}function hideStackFrames(fn){const hidden=nodeInternalPrefix+fn.name;Object.defineProperty(fn,"name",{value:hidden});return fn}function aggregateTwoErrors(innerError,outerError){if(innerError&&outerError&&innerError!==outerError){if(Array.isArray(outerError.errors)){outerError.errors.push(innerError);return outerError}const err=new AggregateError([outerError,innerError],outerError.message);err.code=outerError.code;return err}return innerError||outerError}class AbortError extends Error{constructor(message="The operation was aborted",options=undefined){if(options!==undefined&&typeof options!=="object"){throw new codes.ERR_INVALID_ARG_TYPE("options","Object",options)}super(message,options);this.code="ABORT_ERR";this.name="AbortError"}}E("ERR_ASSERTION","%s",Error);E("ERR_INVALID_ARG_TYPE",(name,expected,actual)=>{assert(typeof name==="string","'name' must be a string");if(!Array.isArray(expected)){expected=[expected]}let msg="The ";if(name.endsWith(" argument")){msg+=`${name} `}else{msg+=`"${name}" ${name.includes(".")?"property":"argument"} `}msg+="must be ";const types=[];const instances=[];const other=[];for(const value of expected){assert(typeof value==="string","All expected entries have to be of type string");if(kTypes.includes(value)){types.push(value.toLowerCase())}else if(classRegExp.test(value)){instances.push(value)}else{assert(value!=="object",'The value "object" should be written as "Object"');other.push(value)}}if(instances.length>0){const pos=types.indexOf("object");if(pos!==-1){types.splice(types,pos,1);instances.push("Object")}}if(types.length>0){switch(types.length){case 1:msg+=`of type ${types[0]}`;break;case 2:msg+=`one of type ${types[0]} or ${types[1]}`;break;default:{const last=types.pop();msg+=`one of type ${types.join(", ")}, or ${last}`}}if(instances.length>0||other.length>0){msg+=" or "}}if(instances.length>0){switch(instances.length){case 1:msg+=`an instance of ${instances[0]}`;break;case 2:msg+=`an instance of ${instances[0]} or ${instances[1]}`;break;default:{const last=instances.pop();msg+=`an instance of ${instances.join(", ")}, or ${last}`}}if(other.length>0){msg+=" or "}}switch(other.length){case 0:break;case 1:if(other[0].toLowerCase()!==other[0]){msg+="an "}msg+=`${other[0]}`;break;case 2:msg+=`one of ${other[0]} or ${other[1]}`;break;default:{const last=other.pop();msg+=`one of ${other.join(", ")}, or ${last}`}}if(actual==null){msg+=`. Received ${actual}`}else if(typeof actual==="function"&&actual.name){msg+=`. Received function ${actual.name}`}else if(typeof actual==="object"){var _actual$constructor;if((_actual$constructor=actual.constructor)!==null&&_actual$constructor!==undefined&&_actual$constructor.name){msg+=`. Received an instance of ${actual.constructor.name}`}else{const inspected=inspect(actual,{depth:-1});msg+=`. Received ${inspected}`}}else{let inspected=inspect(actual,{colors:false});if(inspected.length>25){inspected=`${inspected.slice(0,25)}...`}msg+=`. Received type ${typeof actual} (${inspected})`}return msg},TypeError);E("ERR_INVALID_ARG_VALUE",(name,value,reason="is invalid")=>{let inspected=inspect(value);if(inspected.length>128){inspected=inspected.slice(0,128)+"..."}const type=name.includes(".")?"property":"argument";return`The ${type} '${name}' ${reason}. Received ${inspected}`},TypeError);E("ERR_INVALID_RETURN_VALUE",(input,name,value)=>{var _value$constructor;const type=value!==null&&value!==undefined&&(_value$constructor=value.constructor)!==null&&_value$constructor!==undefined&&_value$constructor.name?`instance of ${value.constructor.name}`:`type ${typeof value}`;return`Expected ${input} to be returned from the "${name}"`+` function but got ${type}.`},TypeError);E("ERR_MISSING_ARGS",(...args)=>{assert(args.length>0,"At least one arg needs to be specified");let msg;const len=args.length;args=(Array.isArray(args)?args:[args]).map(a=>`"${a}"`).join(" or ");switch(len){case 1:msg+=`The ${args[0]} argument`;break;case 2:msg+=`The ${args[0]} and ${args[1]} arguments`;break;default:{const last=args.pop();msg+=`The ${args.join(", ")}, and ${last} arguments`}break}return`${msg} must be specified`},TypeError);E("ERR_OUT_OF_RANGE",(str,range,input)=>{assert(range,'Missing "range" argument');let received;if(Number.isInteger(input)&&Math.abs(input)>2**32){received=addNumericalSeparator(String(input))}else if(typeof input==="bigint"){received=String(input);if(input>2n**32n||input<-(2n**32n)){received=addNumericalSeparator(received)}received+="n"}else{received=inspect(input)}return`The value of "${str}" is out of range. It must be ${range}. Received ${received}`},RangeError);E("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);E("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);E("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);E("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);E("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);E("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);E("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);E("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);E("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);E("ERR_STREAM_WRITE_AFTER_END","write after end",Error);E("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);module.exports={AbortError:AbortError,aggregateTwoErrors:hideStackFrames(aggregateTwoErrors),hideStackFrames:hideStackFrames,codes:codes}},{"./util":41}],40:[function(require,module,exports){"use strict";module.exports={ArrayIsArray(self){return Array.isArray(self)},ArrayPrototypeIncludes(self,el){return self.includes(el)},ArrayPrototypeIndexOf(self,el){return self.indexOf(el)},ArrayPrototypeJoin(self,sep){return self.join(sep)},ArrayPrototypeMap(self,fn){return self.map(fn)},ArrayPrototypePop(self,el){return self.pop(el)},ArrayPrototypePush(self,el){return self.push(el)},ArrayPrototypeSlice(self,start,end){return self.slice(start,end)},Error:Error,FunctionPrototypeCall(fn,thisArgs,...args){return fn.call(thisArgs,...args)},FunctionPrototypeSymbolHasInstance(self,instance){return Function.prototype[Symbol.hasInstance].call(self,instance)},MathFloor:Math.floor,Number:Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(self,props){return Object.defineProperties(self,props)},ObjectDefineProperty(self,name,prop){return Object.defineProperty(self,name,prop)},ObjectGetOwnPropertyDescriptor(self,name){return Object.getOwnPropertyDescriptor(self,name)},ObjectKeys(obj){return Object.keys(obj)},ObjectSetPrototypeOf(target,proto){return Object.setPrototypeOf(target,proto)},Promise:Promise,PromisePrototypeCatch(self,fn){return self.catch(fn)},PromisePrototypeThen(self,thenFn,catchFn){return self.then(thenFn,catchFn)},PromiseReject(err){return Promise.reject(err)},ReflectApply:Reflect.apply,RegExpPrototypeTest(self,value){return self.test(value)},SafeSet:Set,String:String,StringPrototypeSlice(self,start,end){return self.slice(start,end)},StringPrototypeToLowerCase(self){return self.toLowerCase()},StringPrototypeToUpperCase(self){return self.toUpperCase()},StringPrototypeTrim(self){return self.trim()},Symbol:Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(self,buf,len){return self.set(buf,len)},Uint8Array:Uint8Array}},{}],41:[function(require,module,exports){"use strict";const bufferModule=require("buffer");const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;const Blob=globalThis.Blob||bufferModule.Blob;const isBlob=typeof Blob!=="undefined"?function isBlob(b){return b instanceof Blob}:function isBlob(b){return false};class AggregateError extends Error{constructor(errors){if(!Array.isArray(errors)){throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)}let message="";for(let i=0;i{resolve=res;reject=rej});return{promise:promise,resolve:resolve,reject:reject}},promisify(fn){return new Promise((resolve,reject)=>{fn((err,...args)=>{if(err){return reject(err)}return resolve(...args)})})},debuglog(){return function(){}},format(format,...args){return format.replace(/%([sdifj])/g,function(...[_unused,type]){const replacement=args.shift();if(type==="f"){return replacement.toFixed(6)}else if(type==="j"){return JSON.stringify(replacement)}else if(type==="s"&&typeof replacement==="object"){const ctor=replacement.constructor!==Object?replacement.constructor.name:"";return`${ctor} {}`.trim()}else{return replacement.toString()}})},inspect(value){switch(typeof value){case"string":if(value.includes("'")){if(!value.includes('"')){return`"${value}"`}else if(!value.includes("`")&&!value.includes("${")){return`\`${value}\``}}return`'${value}'`;case"number":if(isNaN(value)){return"NaN"}else if(Object.is(value,-0)){return String(value)}return value;case"bigint":return`${String(value)}n`;case"boolean":case"undefined":return String(value);case"object":return"{}"}},types:{isAsyncFunction(fn){return fn instanceof AsyncFunction},isArrayBufferView(arr){return ArrayBuffer.isView(arr)}},isBlob:isBlob};module.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},{buffer:15}],42:[function(require,module,exports){const{Buffer}=require("buffer");"use strict";const{ObjectDefineProperty,ObjectKeys,ReflectApply}=require("./ours/primordials");const{promisify:{custom:customPromisify}}=require("./ours/util");const{streamReturningOperators,promiseReturningOperators}=require("./internal/streams/operators");const{codes:{ERR_ILLEGAL_CONSTRUCTOR}}=require("./ours/errors");const compose=require("./internal/streams/compose");const{pipeline}=require("./internal/streams/pipeline");const{destroyer}=require("./internal/streams/destroy");const eos=require("./internal/streams/end-of-stream");const internalBuffer={};const promises=require("./stream/promises");const utils=require("./internal/streams/utils");const Stream=module.exports=require("./internal/streams/legacy").Stream;Stream.isDisturbed=utils.isDisturbed;Stream.isErrored=utils.isErrored;Stream.isReadable=utils.isReadable;Stream.Readable=require("./internal/streams/readable");for(const key of ObjectKeys(streamReturningOperators)){const op=streamReturningOperators[key];function fn(...args){if(new.target){throw ERR_ILLEGAL_CONSTRUCTOR()}return Stream.Readable.from(ReflectApply(op,this,args))}ObjectDefineProperty(fn,"name",{__proto__:null,value:op.name});ObjectDefineProperty(fn,"length",{__proto__:null,value:op.length});ObjectDefineProperty(Stream.Readable.prototype,key,{__proto__:null,value:fn,enumerable:false,configurable:true,writable:true})}for(const key of ObjectKeys(promiseReturningOperators)){const op=promiseReturningOperators[key];function fn(...args){if(new.target){throw ERR_ILLEGAL_CONSTRUCTOR()}return ReflectApply(op,this,args)}ObjectDefineProperty(fn,"name",{__proto__:null,value:op.name});ObjectDefineProperty(fn,"length",{__proto__:null,value:op.length});ObjectDefineProperty(Stream.Readable.prototype,key,{__proto__:null,value:fn,enumerable:false,configurable:true,writable:true})}Stream.Writable=require("./internal/streams/writable");Stream.Duplex=require("./internal/streams/duplex");Stream.Transform=require("./internal/streams/transform");Stream.PassThrough=require("./internal/streams/passthrough");Stream.pipeline=pipeline;const{addAbortSignal}=require("./internal/streams/add-abort-signal");Stream.addAbortSignal=addAbortSignal;Stream.finished=eos;Stream.destroy=destroyer;Stream.compose=compose;ObjectDefineProperty(Stream,"promises",{__proto__:null,configurable:true,enumerable:true,get(){return promises}});ObjectDefineProperty(pipeline,customPromisify,{__proto__:null,enumerable:true,get(){return promises.pipeline}});ObjectDefineProperty(eos,customPromisify,{__proto__:null,enumerable:true,get(){return promises.finished}});Stream.Stream=Stream;Stream._isUint8Array=function isUint8Array(value){return value instanceof Uint8Array};Stream._uint8ArrayToBuffer=function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk.buffer,chunk.byteOffset,chunk.byteLength)}},{"./internal/streams/add-abort-signal":20,"./internal/streams/compose":22,"./internal/streams/destroy":23,"./internal/streams/duplex":24,"./internal/streams/end-of-stream":26,"./internal/streams/legacy":28,"./internal/streams/operators":29,"./internal/streams/passthrough":30,"./internal/streams/pipeline":31,"./internal/streams/readable":32,"./internal/streams/transform":34,"./internal/streams/utils":35,"./internal/streams/writable":36,"./ours/errors":39,"./ours/primordials":40,"./ours/util":41,"./stream/promises":43,buffer:15}],43:[function(require,module,exports){"use strict";const{ArrayPrototypePop,Promise}=require("../ours/primordials");const{isIterable,isNodeStream,isWebStream}=require("../internal/streams/utils");const{pipelineImpl:pl}=require("../internal/streams/pipeline");const{finished}=require("../internal/streams/end-of-stream");require("../../lib/stream.js");function pipeline(...streams){return new Promise((resolve,reject)=>{let signal;let end;const lastArg=streams[streams.length-1];if(lastArg&&typeof lastArg==="object"&&!isNodeStream(lastArg)&&!isIterable(lastArg)&&!isWebStream(lastArg)){const options=ArrayPrototypePop(streams);signal=options.signal;end=options.end}pl(streams,(err,value)=>{if(err){reject(err)}else{resolve(value)}},{signal:signal,end:end})})}module.exports={finished:finished,pipeline:pipeline}},{"../../lib/stream.js":42,"../internal/streams/end-of-stream":26,"../internal/streams/pipeline":31,"../internal/streams/utils":35,"../ours/primordials":40}]},{},[10])(10)});